String 方法repalceAll,replaceFirst的坑

代码

package test;

public class Test1 {

	//去除 \\2.3 这样的字符
	public static void main(String[] args) {
		String a="D:\\temp\\Thinking\\chapter 2\\Object\\2.3\\";
		boolean matches = a.matches("^.+\\\\\\d+(\\.\\d+)?\\\\$");
		System.out.println(matches);
		String replaceAll = a.replaceAll("^\\\\\\d+(\\.\\d+)?$", "");
		String replaceAll2 = a.replaceAll("\\\\\\d+(\\.\\d+)?", "");
		String replaceAll3 = a.replaceFirst("^\\\\\\d+(\\.\\d+)?$", "");
		String replaceAll4 = a.replaceFirst("\\\\\\d+(\\.\\d+)?", "");
		System.out.println(replaceAll);
		System.out.println(replaceAll2);
		System.out.println(replaceAll3);
		System.out.println(replaceAll4);
	}
}

结果

true
D:\temp\Thinking\chapter 2\Object\2.3\
D:\temp\Thinking\chapter 2\Object\
D:\temp\Thinking\chapter 2\Object\2.3\
D:\temp\Thinking\chapter 2\Object\

结论

String 的replaceAll,replaceFirst的正则表达式,不能加上 开始与结束符号;

你可能感兴趣的:(java)