Case-insensitive replaceAll in Java : with example

Case-insensitive replaceAll in Java : with example

How to replace case insensitive substrings in Java. Normally we replace string by any character or any special character or whatever we want, but sometimes we want to replace a word in the whole string by case insensitive.

Regular Expression

The replaceAll function in the java.lang.String class replaces all substring found in that matches the regular expression to replace. Let's see the example:

String sentence = "The president said, “Work, work, and work,” are the keys to success.";
String result = sentence.replaceAll("work", "hard work");
System.out.println("Input sentence : " + sentence);
System.out.println("Output sentence : " + result);

Output:

Input: The president said, “Work, work, and work,” are the keys to success.
Output: The president said, “Work, hard work, and hard work,” are the keys to success.

In this example, we are giving "work" to replace so that all "work" words are replaced by "hard work". But "Work" is not replaced by "hard work" because "W" is a capital letter in this word. So, Let's take an example with a capital letter for "W" in "word".

How to create a dynamic string

String sentence = "The president said, “Work, work, and work,” are the keys to success.";
String result = sentence.replaceAll("Work", "hard work");
System.out.println("Input sentence : " + sentence);
System.out.println("Output sentence : " + result);

Output:

Input: The president said, “Work, work, and work,” are the keys to success.
Output: The president said, “hard work, work, and work,” are the keys to success.

Special Character

In the above example, the just reverse of the previous example, but we want to replaceAll case-insensitive in Java. So now let's take an example of that, In this example, we will use "(?i)" special character with our replacement keyword.

Loading...
String sentence = "The president said, “Work, work, and work,” are the keys to success.";
String result = sentence.replaceAll("(?i)work", "hard work");
System.out.println("Input sentence : " + sentence);
System.out.println("Output sentence : " + result);

Output:

Input: The president said, “Work, work, and work,” are the keys to success.
Output: The president said, “hard work, hard work, and hard work,” are the keys to success.

After using "(?i)" with my replacement word we find that, all occurrence of "word" is replaced with "hard word".

Related posts

Write a comment