Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex for replacing exact match

Tags:

java

regex

My java app is trying to modify the following line from a file:

static int a = 5;

The goal is to replace 'a' with 'mod_a'.

Using a simple string.replace(var_name, "mod" + var_name) gives me the following:

stmod_atic int mod_a = 5;

Which is quite simply wrong. Googling around i found that you can prepend "\b" and then var_name has to represent the beginning of a word, however, string.replace("\\b" + var_name, "mod" + var_name) does absolutely nothing :(

(I also tested with "\b" instead of "\b")

like image 339
Robin Heggelund Hansen Avatar asked Feb 12 '26 05:02

Robin Heggelund Hansen


1 Answers

  • \b here is a regular expression meaning a word boundary, so it's pretty much what you want.
  • String.replace() does not use regular expressions (so \b will match only the literal \b).
  • String.replaceAll() does use regular expressions
  • You can also use \b both before and after your variable, to avoid replacing "aDifferentVariable" with "mod_aDifferentVariable".

So the a possible solution would be this:

String result = "static int a = 5;".replaceAll("\\ba\\b", "mod_a");

or more general:

static String prependToWord(String input, String word, String prefix) {
    return input.replaceAll("\\b" + Pattern.quote(word) + "\\b", Matcher.quoteReplacement(prefix + word));
}

Note that I use Pattern.qoute() in case word contains any characters that have a meaning in regular expressions. For a similar reason Matcher.quoteReplacement() is used on the replacement String.

like image 141
Joachim Sauer Avatar answered Feb 14 '26 19:02

Joachim Sauer



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!