【问题标题】:replaceFirst , Why can't special symbols be replaced?replace首先,为什么不能替换特殊符号?
【发布时间】:2022-11-21 20:01:45
【问题描述】:

replace首先,为什么不能替换特殊符号?

System.out.println(cal); // 1 * 1 + 1 <==== ???

package com;

import org.apache.commons.lang.StringUtils;

public class Test {

    public static void main(String[] args) {

        String cal = "[aaa] * [aaa] + [bbb]";

        int cnt = StringUtils.countMatches(cal, "[");

        String delStr = "";

        for (int i = 0; i < cnt; i++) {
            delStr = cal.substring(cal.indexOf("["), cal.indexOf("]") + 1);
            cal = cal.replaceFirst("["+delStr +"]", "1");
        }

        System.out.println(cal); // 1 * 1 + 1 <==== ???
    }
}

【问题讨论】:

  • 您应该尝试告诉我们代码应该做什么,[] 是正则表达式中的特殊字符,需要转义,请查看正则表达式:w3schools.com/java/java_regex.asp

标签: java


【解决方案1】:

正则表达式中使用的特殊符号需要使用 进行转义,或者在 Pattern.quote 的帮助下将整个表达式视为字符串文字,它基本上用 Q 和 @987654324 对包围正则表达式@.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多