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”)
\bhere is a regular expression meaning a word boundary, so it’s pretty much what you want.String.replace()does not use regular expressions (so\bwill match only the literal\b).String.replaceAll()does use regular expressions\bboth before and after your variable, to avoid replacing “aDifferentVariable” with “mod_aDifferentVariable”.So the a possible solution would be this:
or more general:
Note that I use
Pattern.qoute()in casewordcontains any characters that have a meaning in regular expressions. For a similar reasonMatcher.quoteReplacement()is used on the replacement String.