Java字符串替换(replace()、replaceFirst()、replaceAll())

1、replace()方法

    public static void main(String[] args){
        String str = "hello world, hello java";
        str = str.replace("h","H");
        System.out.println(str);
    }
//输出:Hello world, Hello java

2、replaceFirst()方法

public static void main(String[] args){
        String str = "hello world, hello java";
        str = str.replaceFirst("hello","Hi");
        System.out.println(str);
    }
//输出:Hi world, hello java

3、replaceAll()方法

public static void main(String[] args){
        String str = "hello world, hello java";
        str = str.replaceAll("hello","Hi");
        System.out.println(str);
    }
//输出:Hi world, Hi java

4、扩展:将字符串 time:[* TO ] 中第二个替换为 test

//将字符串 time:[* TO *] 中第二个*替换为 test
    public static void main(String[] args){
        String test = "time:[* TO *TO]";
        String result1 = test.replaceAll("(\\*)(.*?)(\\1)(.*?)", "$1$2test$4");
        System.out.println("原字符串:" + test);
        System.out.println("替换后:" + result1);
    }
//原字符串:time:[* TO *TO]
//替换后:time:[* TO testTO]

你可能感兴趣的:(Java字符串替换(replace()、replaceFirst()、replaceAll()))