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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:50:00  来源:igfitidea点击:

String pattern matching problem in Java

javaregex

提问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.replaceAllis 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.replacelike 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”和括号。如果您看不到此消息,则应检查记录/捕获/显示异常的方式。它可以为您节省一些将来的麻烦。