Search code examples
javaregexstringreplaceall

RegExp - Replace exact String


I need a help in regular expression, I am trying to replace "Inc" with "LLC" for many string.

I used this code in java :

String newValue = newValue.replaceAll("(?i)Inc[^\\w]","LLC");

But the result is incorrect, one char is removed after replacing :

Exp: CONSULTANTS, INC. ("ABC") ==> CONSULTANTS, LLC ("ABC") // the "." was removed.

Please note that i have used [^\w] to prevent replacing "inc" in sentences like "include".


Solution

  • You can use \b for word boundaries if there is no special literals in the string like ^ or ():

    String s = "include inc".replaceAll("(?i)\\binc\\b", "LLC");
    System.out.println(s); // (?i) is for case insensitive.
    

    Above approach would fail if you use special characters in place of inc like ^inc. You can use Pattern.quote(s) for it to work.

    If there are special characters then you can use quoted literals \Q...\E. Utility method using quoted literals:

    public static String replaceExact(String str, String from, String to) {
        return str.replaceAll("(?<!\\w)\\Q" + from + "\\E(?!\\w)", to);
    }
    

    Note: Pattern.quote("wor^d") will return \\Qwor^d\\E which is same as above regex.