Reputation: 80
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
Upvotes: 1
Views: 1667
Reputation: 5931
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:
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")
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; seeMatcher.replaceAll
. UseMatcher.quoteReplacement(java.lang.String)
to suppress the special meaning of these characters, if desired.
Upvotes: 2