[英]how to Split String By \ in java
I am having problem to split string in java. 我在用java拆分字符串时遇到问题。 it gives
java.util.regex.Pattern.error
. 它给出了
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). One\\Two\\Three
不是有效的字符串文字(您需要引号,并且需要转义反斜杠)。
String name = "One\\Two\\Three.";
String[] str = name.split("\\\\");
for(int i =0; i < str.length ; i++)
System.out.println(str[i]);
works fine . 工作正常 。
String#split
expects a regular expression. String#split
需要一个正则表达式。 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 "\\\\\\\\"
. 反斜杠字符在正则表达式中具有特殊含义,因此您需要使用另一个反斜杠对其进行转义:
\\\\
现在,由于Java字符串文字中的反斜杠字符也具有特殊含义,因此您必须再次将它们每个都加倍,从而导致"\\\\\\\\"
。
你错过了报价
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 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(). 您不能在其中编写测试字符串和测试模式,它可以调用方法matchs(),lookingAt(),find()和reset()。 Also it translates your pattern to Java code (escaping the backslashes and such).
它还将您的模式转换为Java代码(转义反斜杠等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.