开发者

String pattern matching problem in Java

开发者 https://www.devze.com 2022-12-16 01:36 出处:网络
In my program when I\'m using line.replaceAll(\"(\", \"_\"); I got a RuntimeException: at java.util.regex.Pattern.error(Unknown Source)

In my program when I'm using

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

I got a 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.r开发者_开发知识库eplaceAll(Unknown Source)
 at Processing.processEarly(Processing.java:95)
 at Processing.main(Processing.java:34)

Is there any reason? How can we avoid it?


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:

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

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

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


The error message above the stack trace is (somewhat) helpful:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消