Why doesn’t this work?
"hello[world".split("\[")
and this does:
"hello[world".split("\\[")
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is actually two escapes in different contexts, due to the fact that the argument is a regular expression represented as a string.
The
[has to be escaped because otherwise it would have a special meaning in the regular expression. The escape for the regular expression would make it\[. But then the\has to be escaped as it has special meaning in a string (for escaping and for representing characters by numeric value).It can be much worse, as the
\character is used for escaping in both contexts. If you want to split by the\character, you have to escape it (\\) for the regular expression usage, but then you have two\characters, which both have to be escaped in string context. The usage in the original string you are splitting would also need the escape if you’re writing it as a constant, so the analogous split would look like: