Printable Version Printable Version

Case Insensitive replaceAll in Java

Apr 23rd, 2009 | By admin | Category: Java

java.lang.String.replaceAll(String regex, String replacement) method replaces each substring that matches the given regular expression with the given replacement. But Often we fall in trouble to do case sensitive replacement.
Say my code has a string "I am a tesTeR" and I want to replace the substring "tesTeR" with "Developer" . Now In my programming, the substring "tesTer" is dynamic and defined by the User of my application and they are allowed to pass the substring as , "Tester" ,"TesTER","testeR" . . . etc.Now to achieve the case sensitive replacement we can use the flag (?i) with regex . Look at the following java program :

package com.etechguide.java.string;
/**
*
* Case Sensitive String Replace All
*
*/
public class CSSReplaceAll {
public static void main(String[] args) {
String str = "I am a TesteR";
System.out.println("input : " + str);
str = str.replaceAll("(?i)tester", "developer");
System.out.println("output : " + str);
}
}

If you run the program ,

input : I am a TesteR
output : I am a developer

  • Share/Save/Bookmark
Tags: ,

9 comments
Leave a comment »

  1. great find.

  2. really nice

  3. Thanks Amit.
    - admin
    Please do share your valuable learnings.Lets make this blog more useful.
    http://etechguide.in

  4. Thanks raveman.
    - admin
    Please do share your valuable learnings.Lets make this blog more useful.
    http://etechguide.in

  5. Really a great finding. Hope its useful for many people.

  6. Very nice.
    What you show here is a case insensitive replace, therefore you had to use the (?i) operator.
    Case sensitive is the opposite of what you want – replace only strings that match the exact case.

    Asaf

  7. Thanks Asaf,
    It’s true that , the heading should be changed to case insensitive matching .. :)

  8. “java.lang.String.replaceAll(String regex, String replacement) method replaces each substring that matches the given regular expression with the given replacement.”

    The key words in this description are “regular expression”. That should make this “finding” as obvious as it can be: provide the regular expression, and *anything that matches it* will be replaced. Many people don’t read the javadocs, and therefore _assume_ that the function only replaces the exact matches of the provided string. For such folks, this post is a revelation.

  9. thanx man
    was looking for case insenstive replace all
    coded my own but was errorenous…

Leave Comment