Java regex for replacing exact match
java, regex
Solution
- `\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.
Problem
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")