java split("\\") 和错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13175129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:46:15  来源:igfitidea点击:

split("\\") and error

java

提问by evilYoung

String str = "\u0054\u0068\u0069\u006e\u006b\u0050\u0061\u0064";

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

but this error occured.

但发生了这个错误。

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1

线程“main”中的异常 java.util.regex.PatternSyntaxException:索引 1 附近出现意外内部错误

回答by John Woo

it should be

它应该是

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

the reason why is because in Regex, \has special meaning so you need to escape it into \\.

之所以会这样,是因为 in Regex,\有特殊的意义,所以你需要把它转义成\\.

and in java, \\should be equal to "\\\\"

在java中,\\应该等于"\\\\"

回答by Mukul Goel

String.split(String regex)method take as parameter a RegEx.

String.split(String regex)方法以参数 a 为参数RegEx

RegEX for \is \\\\

正则表达式\就是\\\\

Try

尝试

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

Reason why we use "\\\\",

我们使用的原因"\\\\"

Regex for \is \\

正则表达式\就是\\

Now \\is treated as \apply the escape character logic ( \n= new line , \\= \)

现在\\被视为\应用转义字符逻辑(\n=换行,\\= \

So to have "\\"we use "\\\\"

所以让"\\"我们使用"\\\\"

Hope its not confusing.. :D

希望它不会令人困惑.. :D

回答by assylias

That does not make much sense. Your original string uses unicode characters and is equal to ThinkPad. So there is no slash to remove anyway.

那没有多大意义。您的原始字符串使用 unicode 字符并且等于ThinkPad. 所以无论如何都没有要删除的斜线。

In other words, the code below prints ThinkPadtwice:

换句话说,下面的代码打印了ThinkPad两次:

public static void main(String args[]) {
    String str = "\u0054\u0068\u0069\u006e\u006b\u0050\u0061\u0064";
    System.out.println(str);
    String[] strArray = str.split("\\");
    System.out.println(Arrays.toString(strArray));
}

Or even clearer, the code below prints true:

或者更清楚的是,下面的代码打印为真:

public static void main(String args[]) {
    String str = "\u0054\u0068\u0069\u006e\u006b\u0050\u0061\u0064";
    String str2 = "ThinkPad";
    System.out.println(str == str2);
}

回答by Thai Tran

For the general solution about escaping: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html

有关转义的一般解决方案:http: //commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html

String str = "\u0054\u0068\u0069\u006e\u006b\u0050\u0061\u0064";
String[] strArray = str.split(StringEscapeUtils.escapeJava("\"));