Java中的字符串模式匹配问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2033161/
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
String pattern matching problem in Java
提问by Mahesh Gupta
In my program when I'm using
在我的程序中使用时
line.replaceAll("(", "_");
I got a RuntimeException
:
我得到了一个RuntimeException
:
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.accept(Unknown Source)
at java.util.regex.Pattern.group0(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at Processing.processEarly(Processing.java:95)
at Processing.main(Processing.java:34)
Is there any reason? How can we avoid it?
有什么原因吗?我们怎样才能避免呢?
采纳答案by David M
The first argument to string.replaceAll
is a regular expression, not just a string. The opening left bracket is a special character in a regex, so you must escape it:
的第一个参数string.replaceAll
是一个正则表达式,而不仅仅是一个字符串。左括号是正则表达式中的一个特殊字符,因此您必须对其进行转义:
line.replaceAll("\(", "_");
Alternatively, since you are replacing a single character, you could use string.replace
like so:
或者,由于您要替换单个字符,您可以string.replace
像这样使用:
line.replace('(', '_');
回答by Ken
The error message above the stack trace is (somewhat) helpful:
堆栈跟踪上方的错误消息(有点)有帮助:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1 ( ^
线程“main”中的异常java.util.regex.PatternSyntaxException:索引1附近的未关闭组(^
(That's what I get in Java 6.) It mentions "regex", "group", and the parenthesis. If you can't see this message, you should check how you're logging/catching/displaying exceptions. It could save you some trouble in the future.
(这就是我在 Java 6 中得到的。)它提到了“regex”、“group”和括号。如果您看不到此消息,则应检查记录/捕获/显示异常的方式。它可以为您节省一些将来的麻烦。