[英]Splitting a string on special char
I have a string "0000_Clothing|0000_Clothing_Men's|0000_Clothing_Men's_Shirts", and i wanted to split this string on "|". 我有一个字符串“ 0000_Clothing | 0000_Clothing_Men's | 0000_Clothing_Men's_Shirts”,我想将此字符串拆分为“ |”。
String CatArray[] = CatContext.split("|");
The above mentioned code is splitting the string into seperate characters like 0,0,0,0,_,C including the | 上面提到的代码将字符串拆分为单独的字符,例如0,0,0,0,_,C,包括|。 symbol. 符号。
What Am i missing here? 我在这里想念什么?
|
is a regex metacharacter, escape it "\\\\|"
是正则表达式元字符,请将其转义为"\\\\|"
Split method expects a regex and you will have to escape | 拆分方法需要正则表达式,因此您必须转义|
You can do either 你可以做
CatContext.split("\\|");
or 要么
CatContext.split("[|]");
Note that public String[] split(String regex) takes a regex . 请注意, public String [] split(String regex)需要一个regex 。
So you should escape the special char |
因此,您应该转义特殊字符 |
. 。 Escaping a regex is done by \\
, but in Java, \\
is written as \\\\
. 转义符由\\
完成,但是在Java中, \\
编写为\\\\
。
When you escape the special character, you're telling Java: 当您转义特殊字符时,您将告诉Java:
"Don't treat |
as the special char |
, treat it as it was the regular char |
". “不要将|
视为特殊字符|
,将其视为常规字符|
”。
Another solution is to use public static String quote(String s) that " Returns a literal pattern String for the specified String ": 另一个解决方案是使用公共静态字符串quote(String s) ,该字符串 “ 返回指定字符串的文字模式字符串 ”:
String[] CatArray = CatContext.split(Pattern.quote("|"));
If you don't want to deal with escaping the pipe (since pipe is a special regex character) then you can use Pattern#quote
: 如果您不想处理转义符(因为管道是特殊的正则表达式字符),则可以使用Pattern#quote
:
String[] catArray = CatContext.split(Pattern.quote("|"));
OR even simpler: 或更简单:
String[] catArray = CatContext.split("\\Q|\\E"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.