将整个单词与字符串中的前导或尾随特殊符号(例如美元)匹配 [英] Matching a whole word with leading or trailing special symbols like dollar in a string
问题描述
我可以使用 Matcher.quoteReplacement替换美元符号.
我可以通过添加边界字符来替换单词:
I can replace dollar signs by using Matcher.quoteReplacement.
I can replace words by adding boundary characters:
from = "\\b" + from + "\\b";
outString = line.replaceAll(from, to);
但是我似乎无法将它们结合起来用美元符号代替单词.
But I can't seem to combine them to replace words with dollar signs.
这是一个例子.我正在尝试将" $ temp4
"(不是 $ temp40
)替换为" register1
".
Here's an example. I am trying to replace "$temp4
" (NOT $temp40
) with "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?
How do I get it to replace $temp4 and only $temp4?
推荐答案
使用明确的单词边界,(?<!\ w)
和(?!\ w)
,而不是与上下文相关的 \ b
:
Use unambiguous word boundaries, (?<!\w)
and (?!\w)
, instead of \b
that are context dependent:
from = "(?<!\\w)" + Pattern.quote(from) + "(?!\\w)";
请参见 正则表达式演示 .
如果当前位置和(?!\ w)
是一个否定的超前查询,如果当前位置右侧紧邻有一个非单词char,则匹配失败.要避免 from
变量中的任何特殊字符,必须使用 Pattern.quote(from)
.
The (?<!\w)
is a negative lookbehind that fails the match if there is a non-word char immediately to the left of the current location and (?!\w)
is a negative lookahead that fails the match if there is a non-word char immediately to the right of the current location. The Pattern.quote(from)
is necessary to escape any special chars in the from
variable.
请参见 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
这篇关于将整个单词与字符串中的前导或尾随特殊符号(例如美元)匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!