public static void main(String[] args) throws Exception {String test = "-1+-2.3-2+-2";test = test.replaceAll("+-", "-");System.out.println(test);}
该代码段是想把表达式中的所有"±"都替换为"-",确出现以下异常:
因为正则表达式中"+“为特殊符号,是量词,表示{1,},因此,要匹配”+“这个字符,需要转义”\+",java中要"\\+"
程序改为:
public static void main(String[] args) throws Exception {String test = "-1+-2.3-2+-2";test = test.replaceAll("\\+-", "-");System.out.println(test);}
结果:
此外,此类特殊符号还有:? * () [] {} ^ $等等