java replace replaceAll 是替换字符串最常用的方法,但实际上用法是有区别的,replace只能传字符不能传正则表达式,replaceAll 默认传入的就是正则表达式。下面是实例测试代码:
public class TestDemo {
public static void main(String[] args) {
//需求:实现在-x.txt替换成-9x.txt
String filename = “F:/kanbox/2014091-4.txt”;
String newname = filename.replaceAll(“-([0-9])”, “-9$1″);
System.out.println(newname);//F:/kanbox/2014091-94.txt
String newname2 = filename.replace(“-([0-9])”, “-9$1″);
System.out.println(newname2);//F:/kanbox/2014091-4.txt,没达到预期效果
String newname3 = filename.replace(“-”, “-9″);
System.out.println(newname3);//F:/kanbox/2014091-94.txt
}
}
扩展知识,api里面的说明:
String java.lang.String.replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression
————————————-
String java.lang.String.replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing “aa” with “b” in the string “aaa” will result in “ba” rather than “ab”.
Parameters:
target The sequence of char values to be replaced
replacement The replacement sequence of char values
历史上的今天: