Do you really know how to use String's replaceAll?

In Java's string replacement, I recently encountered a problem, that is, the replacement target string contains symbols of regular expressions, resulting in an error.

Error example:

public class ReplaceAllTest {

    public static void main(String[] args) {
        String data="小明今天放学回家[遇到一个小偷在偷自行车";
        data=data.replaceAll("(遇到)","抓住");
        System.out.println(data);
    }
}

Results of the: 

 Solution:

//Pattern.quote和Matcher.quoteReplacement防止特殊字符如[导致报错,原理特殊字符,在正则里需要加\\反斜杆进行转义
surplusStr = surplusStr.replaceAll(Pattern.quote(conditionStr),  Matcher.quoteReplacement(""));

Principle: The bottom layer of replaceAll uses regular expressions to replace strings, so if the special symbols are not escaped, an error will be reported when the regular expressions are replaced, and they need to be escaped

Guess you like

Origin blog.csdn.net/qq_38623939/article/details/129839301