简体   繁体   中英

Java regex for replacing exact match

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")

  • \\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.

尝试:

string.replaceAll("\\b" + var_name + "\\b", "mod" + var_name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM