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")); }
实行效果为:
wEl2comE3SouhE0 wEl2comE3SouhE0 welAcomeASouheA 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 替代此字符串一切婚配给定的正则表达式的子字符串。
以上就是Java中replace与replaceAll之间的区分引见(代码示例)的细致内容,更多请关注ki4网别的相干文章!