用于替换完全匹配的Java正则表达式

Rob*_*sen 2 java regex

我的java应用程序正在尝试从文件中修改以下行:

static int a = 5;
Run Code Online (Sandbox Code Playgroud)

目标是用'mod_a'替换'a'.

使用简单的方法string.replace(var_name, "mod" + var_name)给我以下内容:

stmod_atic int mod_a = 5;
Run Code Online (Sandbox Code Playgroud)

这完全是错的.谷歌搜索我发现你可以前置"\ b"然后var_name必须代表一个单词的开头,但是,string.replace("\\b" + var_name, "mod" + var_name)绝对没有任何东西:(

(我也测试了"\ b"而不是"\ b")

Joa*_*uer 9

  • \b这是一个正则表达式,意思是单词边界,所以它几乎就是你想要的.
  • String.replace()没有使用正则表达式(所以\b将只匹配字面\b).
  • String.replaceAll() 确实使用正则表达式
  • 您也可以在变量之前之后使用\b 它们,以避免将"aDifferentVariable"替换为"mod_aDifferentVariable".

所以一个可能的解决方案是:

String result = "static int a = 5;".replaceAll("\\ba\\b", "mod_a");
Run Code Online (Sandbox Code Playgroud)

或更一般:

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

请注意,我使用Pattern.qoute()的情况word包含任何在正则表达式中有意义的字符.由于类似的原因Matcher.quoteReplacement(),在替换字符串上使用.