Reputation: 765
I am having problem to split string in java. it gives java.util.regex.Pattern.error
.
String name = One\Two\Three.
String[] str = name.split("\\");
for(int i =0; i < str.length ; i++)
System.out.println(str[i]);
I put another \ as escape character but not working.
help me.
Upvotes: 0
Views: 243
Reputation: 121
If you want to test your pattern you should use this tool:
http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html
You cant write your test String there and your test Pattern and it can call the methods matches(), lookingAt(), find() and reset(). Also it translates your pattern to Java code (escaping the backslashes and such).
Upvotes: 0
Reputation: 95308
One\Two\Three
is not a valid string literal (you need quotes and you need to escape the backslashes).
String name = "One\\Two\\Three.";
String[] str = name.split("\\\\");
for(int i =0; i < str.length ; i++)
System.out.println(str[i]);
String#split
expects a regular expression. The backslash character has a special meaning inside regular expressions, so you need to escape it by using another backslash: \\
Now because the backslash character also has a special meaning inside Java string literals, you have to double each of these again, resulting in "\\\\"
.
Upvotes: 7
Reputation: 52185
You need to escape it twice:
String name = "One\\Two\\Three."
String[] str = name.split("\\\\");
for(int i =0; i < str.length ; i++)
System.out.println(str[i]);
Upvotes: 0
Reputation: 7740
You have missed the quotes
String name = "One\\Two\\Three".
Upvotes: 1