简体   繁体   中英

how to Split String By \ in java

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.

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]);

works fine .

Explanation

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 "\\\\\\\\" .

你错过了报价

String name = "One\\Two\\Three".

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]);

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).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM