我可以使用 Matcher.quoteReplacement 替换美元符号。
我可以通过添加边界字符来替换单词:
from = "\\b" + from + "\\b";
outString = line.replaceAll(from, to);
但我似乎无法将它们组合起来用美元符号替换单词。
这是一个例子。我正在尝试将“$temp4
”(不是 $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);
输出
"add, $temp4, $temp40, 42"
如何让它替换 $temp4 并且仅替换 $temp4?
最佳答案
使用明确的单词边界,(?<!\w)
和(?!\w)
,而不是 \b
取决于上下文:
from = "(?<!\\w)" + Pattern.quote(from) + "(?!\\w)";
请参阅regex demo .
(?<!\w)
是一个负向后查找,如果当前位置和 (?!\w)
左侧紧邻一个非单词字符,则匹配失败是一个否定的前瞻,如果当前位置右侧紧邻非单词字符,则匹配失败。 Pattern.quote(from)
必须转义 from
中的任何特殊字符变量。
请参阅Java demo :
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
关于java - 将整个单词与字符串中的前导或尾随特殊符号(如美元)匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56903796/