Search code examples
groovy

Groovy How to replace the exact match word in a String


Groovy How to replace the exact match word in a String.

I wanted to replace the exact matched word in a given string in Groovy. and when i tried the below am not getting the exact matched word

def str="My Name is Richards and Richardson"
log.info(str)
str=str.replace("Richards","Praveen")
log.info("After"+str)

Output after executing the above

My Name is Richards and Richardson AfterMy Name is Praveen and Praveenon

Am Looking for the output like : AfterMy Name is Praveen and Richardson

I tried the boundaries \b str=str.replace("\bRichards\b","Praveen") which is in Java and its not working. Looks \b is ba backslash escape sequence in the Groovy

can someone help

def str="My Name is Richards and Richardson"
log.info(str)
str=str.replace("Richards","Praveen")
log.info("After"+str)

expecting:AfterMy Name is Praveen and Richardson


Solution

  • Using boundaries (/b) will not work with String::replace because the method argument does not accept a regular expression pattern but a simple string literal.

    You have two options to get the expected outcome:

    1. Instead of using String::replace you can use String::replaceFirst. As the method name suggests it will replace only the first occurrence of the Richards substring leaving the Richardson as is.

      str = str.replaceFirst("Richards", "Praveen")
      
    2. Instead of using String::replace you can use String::replaceAll, in opposite to String::replace it supports regular expressions so you can use word boundaries tokens

      str = str.replaceAll("\\bRichards\\b","Praveen")
      

    Mind the double slashes!

    Also, according to the String::replaceAll documentation:

    Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.