I have a string as follows
String s = "3|4||5 9|4 0|0 4 8|..."
and I want to split it based on the "|"
appearances. As such, the split should return
["3","4","5 9","4 0,"0 4 8",...]
But, in Java,
s.split("|") = [, 3, |, 4, ...]
In other words, it is splitting by the ""
character, it seems. What is wrong?
The |
character has special meaning in regular expressions, so you must escape it with a backslash. Then you must escape the backslash itself for Java. Try:
s.split("\\|")
The Javadocs for the Pattern
class has lots of details about special characters in regular expressions. See the "Logical operators" section in that page for what |
does.
Note that public String[] split(String regex) takes a regex .
Since |
is a meta character,It works when you escape the special character .
String[] results = result.split("\\|");
or (personally recommending this)
String[] result = result.split(Pattern.quote("|"));
If you use Pattern
Now, |
will be treated as normal character |
and not as the regex meta char |
.
您可以尝试如下
s.split("[|]")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.