[英]Splitting a String in Java
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, 但是,在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. 然后,您必须为Java转义反斜杠本身。 Try: 尝试:
s.split("\\|")
The Javadocs for the Pattern
class has lots of details about special characters in regular expressions. Pattern
类的Javadocs中有许多有关正则表达式中特殊字符的详细信息。 See the "Logical operators" section in that page for what |
请参阅该页面中的“逻辑运算符”部分,以了解|
does. 做。
Note that public String[] split(String regex) takes a regex . 请注意, public String [] split(String regex)需要一个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("|"));
Now, |
现在, |
will be treated as normal character |
将被视为普通字符 |
and not as the regex meta char |
而不是作为正则表达式元字符|
. 。
您可以尝试如下
s.split("[|]")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.