1

I have a String representing a directory, where \ is used to separate folders. I want to split based on "\\":

String address = "C:\\saeed\\test";
String[] splited = address.split("\\");

However, this is giving me a java.util.regex.PatternSyntaxException.

saeed foroughi
  • 1,662
  • 1
  • 13
  • 25

5 Answers5

7

As others have suggested, you could use:

String[] separated = address.split("\\\\");

or you could use:

String[] separated = address.split(Pattern.quote("\\")); 

Also, for reference:

String address = "C:\saeed\test";

will not compile, since \s is not a valid escape sequence. Here \t is interpreted as the tab character, what you actually want is:

String address = "C:\\saeed\\test";

So, now we see that in order to get a \ in a String, we need "\\".

The regular expression \\ matches a single backslash since \ is a special character in regex, and hence must be escaped. Once we put this in quotes, aka turn it into a String, we need to escape each of the backslashes, yielding "\\\\".

Steve P.
  • 14,489
  • 8
  • 42
  • 72
3

String#split() method takes a regex. In regex, you need to escape the backslashes. And then for string literals in Java, you need to escape the backslash. In all, you need to use 4 backslashes:

String[] splited = address.split("\\\\");
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

You need to use \\\\ instead of \\.

The backslash(\) is an escape character in Java Strings.If you want to use backslash as a literal you have to type \\\\ ,as \ is also a escape character in regular expressions.

For more details click here

Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
1

\ has meaning as a part of the regex, so it too must be quoted. Try \\\\.

The Java will have at \\\\, and produce \\ which is what the regex processor needs to obtain \.

Richard Sitze
  • 8,262
  • 3
  • 36
  • 48
0

Use separators:

String address = "C:\saeed\test";
String[] splited = address.split(System.getProperty("file.separator"));
Luis Sep
  • 2,384
  • 5
  • 27
  • 33