Home  >  Article  >  Java  >  Introduction to the difference between replace and replaceAll in Java (code example)

Introduction to the difference between replace and replaceAll in Java (code example)

不言
不言forward
2019-02-19 15:56:115188browse

本篇文章给大家带来的内容是关于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"));
    }

执行结果为:

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 替换此字符串所有匹配给定的正则表达式的子字符串。

The above is the detailed content of Introduction to the difference between replace and replaceAll in Java (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete