When I split the string "1|2|3|4"
using the String.split("|")
I get 8 elements in the array instead of 4. If I use "\\|"
the result is proper. I am guessing this has something todo with regular expressions. Can anybody explain this?
views:
97answers:
3
+5
A:
You're right. |
is a special character for alternation. The regular expression |
means "an empty string or an empty string". So it will split around all empty strings, resulting 1 element for each character in the string. Escaping it \|
make it a normal character.
KennyTM
2010-09-24 20:08:51
why should I tell you my name
2010-09-24 20:11:18
@why: No it's not. See http://download-llnw.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html. You could use `\Q...\E` to make sure the `...` won't be interpreted as special characters.
KennyTM
2010-09-24 20:13:31
@why should I tell you my name: http://www.regular-expressions.info/reference.html
ColinD
2010-09-24 20:14:22
+1
A:
|
is OR
in Java regular expression syntax, basically splitting 1|2|3|4
with |
is equal to telling String#split()
to "split this string between empty OR empty) which means it splits after every character you have in the original string.
Esko
2010-09-24 20:09:23