In this article, we’ll see how to replace case-insensitive literal substrings in Java

replace() method

The Replace() method in the String class is used to replace occurrences of a specific substring with another substring.

To perform case-insensitive replacement, you can combine the String.replace() method with the String.toLowerCase() method.

Following is an example:

public class CaseInsensitiveReplacementExample {

    public static void main(String[] args) {
        String originalText = "The quick brown fox jumped over the Lazy DOG.";
        String searchText = "dog";
        String replacementText = "cat";

        String modifiedText = originalText.replaceAll("(?i)" + searchText, replacementText);
        System.out.println(modifiedText);
    }
}

In the above example, (?i) is used as a flag to make the search case-insensitive.

The replaceAll() method then replaces all occurrences of the substring “dog“.(regardless of case) with “cat”.

Using the Pattern and Matcher class

Pattern and Matcher provide more advanced pattern matching, which is efficient in performing multiple replacements. We can use these classes along with regular expressions.

Following is an example:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CaseInsensitiveReplacementRegexExample {

    public static void main(String[] args) {
        String originalText = "The quick brown fox jumped over the Lazy DOG.";
        String searchText = "dog";
        String replacementText = "cat";

        Pattern pattern = Pattern.compile(searchText, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(originalText);
        String modifiedText = matcher.replaceAll(replacementText);

        System.out.println(modifiedText);
    }
}

In the above example, the Pattern.CASE_INSENSITIVE flag is used when compiling the regular expression pattern. It ensures case-insensitive matching during replacement.

References:

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

Categorized in:

Tagged in: