Java中replace与replaceAll区别
程序员文章站
2022-05-11 14:12:43
看门见山 1.java中replace API: replace(char oldChar, char newChar):寓意为:返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 replace(CharSequence target, CharSe ......
看门见山
1.java中replace api:
replace(char oldchar, char newchar):寓意为:返回一个新的字符串,它是通过用
newchar
替换此字符串中出现的所有 oldchar
得到的。
replace(charsequence target, charsequence replacement):寓意为:使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。
replaceall(string regex, string replacement):寓意为:
使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
可以看出replace的参数是char与charsequence,而replaceall参数为regex(正则表达式)与replacement
2.举个栗子:
1 @test 2 public void teststring(){ 3 string str="wel2come3souhe0"; 4 system.out.println(str.replace("e","e")); 5 system.out.println(str.replace('e','e')); 6 system.out.println(str.replaceall("\\d","a")); 7 system.out.println(str.replaceall("3","9")); 8 }
执行结果为:
1 wel2come3souhe0 2 wel2come3souhe0 3 welacomeasouhea 4 wel2come9souhe0
3.总结结果:replace替换字符与字符串都是一样的,replace可以根据除了字符串替换外还可以正则表达式来进行替换;
4.多了解一个:
replacefirst(string regex, string replacement) 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
举个栗子:
1 @test 2 public void teststring(){ 3 string str="wel2come3souhe0"; 4 system.out.println(str.replacefirst("\\d","a")); 5 }
执行结果为:
welacome3souhe0
总结:只替换第一次出现的匹配的正则表达式;
完毕!
使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。