Java – Replace First Occurrence of String without Regular Expression

Java – Replace First Occurrence of String without Regular Expression

           The String class in Java has a method replaceFirst(String regex, String replacement) which replaces first occurrence of given regular expression with given replacement string. If you want to replace first occurrence of any given string (with Regular Expression), use the following code.

Sample Code:

package test;

import java.util.regex.Pattern;

public class test{
    public static void main(String[] args) {
        //Input String
        String input = "text1 text1";

        //text1 is the string to be replaced
        String result = input.replaceFirst(Pattern.quote("text1"), "replacedString");

        //Output
        System.out.println("Result:" + result);
    }
}

Output:

Result:replacedString text1

[ YOU MAY ALSO LIKE ]

Leave a Reply