Java,如何用字符串中的美元符号替换单词?

joh*_*jik 7 java regex replaceall

我可以通过使用Matcher.quoteReplacement. 我可以通过添加边界字符替换单词来替换美元符号:

from = "\\b" + from + "\\b"; 
outString = line.replaceAll(from, to);
Run Code Online (Sandbox Code Playgroud)

但我似乎无法将它们结合起来用美元符号代替单词.

这是一个例子.我试图用" $temp4" 替换" "(NOT $temp40)register1.

        String line = "add, $temp4, $temp40, 42";
        String to = "register1";
        String from = "$temp4";
        String outString;


        from = Matcher.quoteReplacement(from);
        from = "\\b" + from + "\\b";  //do whole word replacement

        outString = line.replaceAll(from, to);
        System.out.println(outString);
Run Code Online (Sandbox Code Playgroud)

输出

"add, $temp4, $temp40, 42"
Run Code Online (Sandbox Code Playgroud)

如何让它替换$ temp4和$ temp4?

Wik*_*żew 4

使用明确的单词边界,(?<!\w)并且(?!\w),而不是\b依赖于上下文的:

from = "(?<!\\w)" + Pattern.quote(from) + "(?!\\w)";
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示

如果(?<!\w)当前位置左侧紧邻非单词字符,则为负向后查找,如果紧邻当前位置右侧有非单词字符,则(?!\w)匹配失败;如果当前位置右侧紧邻非单词字符,则为负向前查找,则匹配失败。必须Pattern.quote(from)转义from变量中的任何特殊字符。

请参阅Java 演示

String line = "add, $temp4, $temp40, 42";
String to = "register1";
String from = "$temp4";
String outString;

from = "(?<!\\w)" + Pattern.quote(from) + "(?!\\w)";

outString = line.replaceAll(from, to);
System.out.println(outString);
// => add, register1, $temp40, 42
Run Code Online (Sandbox Code Playgroud)