I have a String = \"Hello-new-World\". And when i use the split() method with different regex values, it acts differently.
String str = \"Hello-new-world\"
Strin
It is a metacharacter. Escape it with a backslash, like this: "\\|"
Pipe is special regex symbol which means OR
, if you want to split by pipe then escape it in your regex:
String[] strbuf = str.split("\\|");
OR
String[] strbuf = str.split("[|]");
Presumably you're splitting on "|"
in the second case - and |
has a special meaning within regular expressions. If you want to split on the actual pipe character, you should escape it:
String[] bits = whole.split(Pattern.quote("|"));
str.split("|");
means something different. String#split
uses regex, and |
is a metacharacter, so that string means: split off of the empty string or off of the empty string. That is why your string gets split on every character.
There are a few ways of doing what you expect (use these as the string to split off of):
"\\|"
Which means to escape the metacharacter.
"[|]"
Puts the metacharacter in a character class.
"\\Q|\\E"
Puts the metacharacter in a quote
split method takes regular expression as input. The pipe is a special character for regular expression, so if you want to use it tou need to escape the special character. Ther are multiple solutions:
You need to escape the "pipe" character
str.split("\\|");
Or you can use the helper quote:
str.split(Regexp.quote("|"))
Or between sqares:
str.split("[|]");
The pipe has different meaning in regular expression, so if you want to use it you need to escape the special character.
str.split("\\|");