Splitting a string on the double pipe(||) using String.split()
13,517
Solution 1
String.split()
uses regular expressions. You need to escape the string that you want to use as divider.
Pattern has a method to do this for you, namely Pattern.quote(String s)
.
String[] split = str.split(Pattern.quote("||"));
Solution 2
You must escape every single |
like this str.split("\\|\\|")
Solution 3
try this bellow :
String[] strArry = str.split("\\|\\|");
Author by
FarSh018
Updated on June 16, 2022Comments
-
FarSh018 almost 2 years
I'm trying to split the string with double pipe(||) being the delimiter.String looks something like this:
String str ="[email protected]||[email protected]||[email protected]";
i'm able to split it using the StringTokeniser.The javadoc says the use of this class is discouraged and instead look at String.split as option.
StringTokenizer token = new StringTokenizer(str, "||");
The above code works fine.But not able to figure out why below string.split function not giving me expected result..
String[] strArry = str.split("\\||");
Where am i going wrong..?
-
CsBalazsHungary about 11 yearsisn't it "\|\|"? Am I mistaken?
-
gtgaxiola about 11 years@CsBalazsHungary you also must escape the `\` since is also a meta character
-
nfechner about 11 years@CsBalazsHungary You also need to escape the `\`, because it's the Java string escape sequence.
-
Tim Goodman about 11 years@CsBalazsHungary Because it's RegEx, you need to escape
|
as\|
. But because the RegEx is being built from a string, you need to additionally escape \ as \\. -
Sentry about 11 years@CsBalazsHungary No, because that would be a Java-escape, but we want a regex-escape
-
Toon Casteele about 11 yearsOh, didn't know
|
was a regex char. I'll get the hang of that regex soon :p -
CsBalazsHungary about 11 years@gtgaxiola Oh ok, thanks, I didn't use this yet just with \"! I mean not with regex