Java中字符串模式匹配问题。

时间:2022-09-13 07:48:27

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?

有什么原因吗?我们怎样才能避免它呢?

2 个解决方案

#1


37  

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:

第一个字符串参数。replaceAll是一个正则表达式,而不仅仅是字符串。左括号是regex中的一个特殊字符,所以必须转义为:

line.replaceAll("\\(", "_");

Alternatively, since you are replacing a single character, you could use string.replace like so:

另外,由于要替换单个字符,所以可以使用字符串。取代像这样:

line.replace('(', '_');

#2


2  

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”和括号。如果您看不到这条消息,您应该检查如何记录/捕获/显示异常。这可以为你将来省去一些麻烦。

#1


37  

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:

第一个字符串参数。replaceAll是一个正则表达式,而不仅仅是字符串。左括号是regex中的一个特殊字符,所以必须转义为:

line.replaceAll("\\(", "_");

Alternatively, since you are replacing a single character, you could use string.replace like so:

另外,由于要替换单个字符,所以可以使用字符串。取代像这样:

line.replace('(', '_');

#2


2  

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”和括号。如果您看不到这条消息,您应该检查如何记录/捕获/显示异常。这可以为你将来省去一些麻烦。