Jatin Sehgal
Jatin Sehgal

Reputation: 966

How to split a string according to "\\" or "\"?

I want to split a string "ABC\DEF" ? I have tried

String str = "ABC\DEF";
String[] values1 = str.split("\\");
String[] values2 = str.split("\");

But none seems to be working. Please help.

Upvotes: 1

Views: 149

Answers (4)

nhahtdh
nhahtdh

Reputation: 56829

Note that String.split splits a string by regex.

One correct way1 to specify \ as delimiter, in RAW regex is:

\\

Since \ is special character in regex, you need to escape it to specify the literal \.

Putting the regex in string literal, you need to escape again, since \ is also escape character in string literal. Therefore, you end up with:

"\\\\"

So your code should be:

str.split("\\\\")

Note that this splits on every single instance of \ in the string.

Footnote

1 Other ways (in RAW regex) are:

\x5C
\0134
\u005C

In string literal (even worse than the quadruple escaping):

"\\x5C"
"\\0134"
"\\u005C"

Upvotes: 2

Varun Bajaj
Varun Bajaj

Reputation: 1043

final String HAY = "_0_";
String str = "ABC\\DEF".replace("\\", HAY);
System.out.println(Arrays.asList(str.split(HAY)));

Upvotes: -1

Kanagaraj M
Kanagaraj M

Reputation: 966

Use it: String str = "ABC\\DEF"; String[] values1 = str.split("\\\\");

Upvotes: 0

fbafelipe
fbafelipe

Reputation: 4952

String.split() expects a regular expression. You need to escape each \ because it is in a java string (by the way you should escape on String str = "ABC\DEF"; too), and you need to escape for the regex. In the end, you will end with this line:

String[] values = str.split("\\\\");

The "\\\\" will be the \\ string, which the regex will interpret as \.

Upvotes: 2

Related Questions