Java 非法转义字符“\(”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20168614/
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
Illegal Escape Character "\("?
提问by user3025996
I need to escape the ( character without the output becoming anything other than..
我需要转义 ( 字符,而输出不会变成除..
a
一种
b
乙
Any help greatly appreciated!
非常感谢任何帮助!
Arbitrary Input:
任意输入:
"a"+"\n" +"("+"b"
"a"+"\n" +"("+"b"
Desired Output:
期望输出:
a
一种
b
乙
//Here are the attempted work-arounds that failed
40 String test = "a"+"\n("+"b";
41 String[] testSplitted = test.split("\n"+"(");
42 System.out.println(testSplitted[0]);
43 System.out.println(testSplitted[1]);
// ("\n"+"\(") ILLEGAL ESCAPE CHARACTER
// ("\n\(") ILLEGAL ESCAPE CHARACTER
// ("\n(") INVALID REGULAR EXPRESSION: UNCLOSED GROUP
// ("\n\(") Output: a \(b (Desired Output: a b)
// ("\n"+"[(]") Output:
a [(]b Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at inputhandler.InputHandler.main(InputHandler.java:43)
Java Result: 1
// ("\n"+"(") Output:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 2
(
^
at java.util.regex.Pattern.error(Pattern.java:1924)
at java.util.regex.Pattern.accept(Pattern.java:1782)
at java.util.regex.Pattern.group0(Pattern.java:2857)
at java.util.regex.Pattern.sequence(Pattern.java:2018)
at java.util.regex.Pattern.expr(Pattern.java:1964)
at java.util.regex.Pattern.compile(Pattern.java:1665)
at java.util.regex.Pattern.<init>(Pattern.java:1337)
at java.util.regex.Pattern.compile(Pattern.java:1022)
at java.lang.String.split(String.java:2313)
at java.lang.String.split(String.java:2355)
at inputhandler.InputHandler.main(InputHandler.java:41)
Java Result: 1
采纳答案by Keppil
To escape (
you need two backslashes since the backslash is a special character in Java strings, and needs to be escaped itself. So, it becomes: \\(
要转义,(
您需要两个反斜杠,因为反斜杠是 Java 字符串中的一个特殊字符,需要对其本身进行转义。所以,它变成: \\(