JAVA中正则表达式的二次转义

需求:格式化金额,替换服务器返回的格式化字符串中的”{0}”为金额

public class Test {
    public static void main(String[] args) {

        String unformattedMoney = "12.00";

        String s = "${0}";

        String regex = "\\{0\\}";

        s = s.replaceAll(regex, unformattedMoney);

        System.out.println(s);

    }
}

执行结果

$12.00

正则表达式中”{“和”}”这样的字符有特殊的意义,所以需要写成”{“。但是”\”本身也是具有特殊意义的转义字符,所以”\”就需要写成”\[“。需要先对”\”进行一次转义

正则中需要转义的字符包括
‘$’, ‘(‘, ‘)’, ‘*’, ‘+’, ‘.’, ‘[‘, ‘]’, ‘?’, ‘\’, ‘^’, ‘{‘, ‘}’, ‘|’

猜你喜欢

转载自blog.csdn.net/u010356768/article/details/80660725