Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression-JAVA

Tags:

java

regex

I have a configuration file in which I am replacing some placeholder(variables) with their actual value after parsing an excel file. I am using the below pattern:

word = word.startsWith("$") ? word.substring(1) : word;
                  return input.replaceAll(Pattern.quote("$"+word),
                   Matcher.quoteReplacement(prefix));

The above is replacing all the sub-strings as well as is case sensitive. For example if I have the below 2 variables: $Building $Building1 , both are different variables. But the above replaces the value of Building in both cases and appends it with "1" in the second case. Could you guys please help me change the pattern. I have tried case_insensitive option but that did not work fine.

like image 970
sahana Avatar asked Mar 17 '26 22:03

sahana


1 Answers

You can use a word boundary \b:

return input.replaceAll(Pattern.quote("$"+word) + "\\b",
                                      Matcher.quoteReplacement(prefix));
like image 64
Eng.Fouad Avatar answered Mar 20 '26 13:03

Eng.Fouad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!