Java开发中replace与replaceAll区别及用法详解
2019-02-18 09:37阅读:
前言
在Java开发中的replace与replaceAll的方法,用到的时候很多,但是有很多小伙伴们的掌握并不是很牢固,那小编在这再给小伙伴们复习一遍,大家跟我一起来学习吧。
正文
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.举个栗子:
@Test
public void testString(){
String
str='wel2come3Souhe0';
System.out.println(str.replace('e','E'));
System.out.println(str.replace('e','E'));
System.out.println(str.replaceAll('\\d','A'));
System.out.println(str.replaceAll('3','9'));
}
执行结果为:
1
wEl2comE3SouhE0
2
wEl2comE3SouhE0
3
welAcomeASouheA
4
wel2come9Souhe0
3.总结结果:
replace替换字符与字符串都是一样的,replace可以根据除了字符串替换外还可以正则表达式来进行替换;
4.多了解一个:
replaceFirst(String regex, String replacement) 使用给定的 replacement
替换此字符串匹配给定的正则表达式的第一个子字符串。
举个栗子:
@Test
public void testString(){
String str='wel2come3Souhe0';
System.out.println(str.replaceFirst('\\d','A'));
}
执行结果为:
welAcome3Souhe0
总结:只替换第一次出现的匹配的正则表达式;完毕!使用给定的 replacement
替换此字符串所有匹配给定的正则表达式的子字符串。