I have a string "0000_Clothing|0000_Clothing_Men's|0000_Clothing_Men's_Shirts", and i wanted to split this string on "|".
String CatArray[] = CatContext.split("|");
The above mentioned code is splitting the string into seperate characters like 0,0,0,0,_,C including the | 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 .
So you should escape the special char |
. Escaping a regex is done by \\
, but in Java, \\
is written as \\\\
.
When you escape the special character, you're telling 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 ":
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
:
String[] catArray = CatContext.split(Pattern.quote("|"));
OR even simpler:
String[] catArray = CatContext.split("\\Q|\\E"));
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.