String pattern matching problem in Java

前端 未结 2 1506
春和景丽
春和景丽 2021-02-18 20:45

In my program when I\'m using

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

I got a RuntimeException:

 at java.util.regex.Pattern         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-18 21:33

    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('(', '_');
    

提交回复
热议问题