我有一个字符串s
和正则表达式。我想用一个替换字符串替换s
中每个正则表达式的匹配。替换字符串可能包含一个或多个反斜杠。为了执行替换,我使用了Matcher
的appendReplacement方法。
appendReplacement
的问题是它忽略了它在替换字符串中遇到的所有反斜杠。因此,如果我尝试用替换字符串"match"
替换字符串"one match"
中的子字符串"a\\b"
,那么appendReplacement
将导致"one ab"
而不是"one a\\b"
*。
Matcher matcher = Pattern.compile("match").matcher("one match");
StringBuffer sb = new StringBuffer();
matcher.find();
matcher.appendReplacement(sb, "a\\b");
System.out.println(sb); // one ab
我看了一下appendReplacement
的代码,发现它跳过了任何遇到的反斜杠:
if (nextChar == '\\') {
cursor++
nextChar = replacement.charAt(cursor);
...
}
如何用包含反斜杠的替换字符串替换每个匹配?
(*) -注意,"a\\b"
中有一个反斜杠,而不是两个。反斜杠刚刚逃脱。
发布于 2014-12-09 12:37:28
您需要双转义反斜杠,即:
matcher.appendReplacement(sb, "a\\\\b");
完整代码:
Matcher matcher = Pattern.compile("match").matcher("one match");
sb = new StringBuffer();
matcher.find();
matcher.appendReplacement(sb, "a\\\\b");
System.out.println(sb); //-> one a/b
因为Java允许您在替换字符串中使用反引用(如$1
、$2
等),并且对反斜杠强制执行与主正则表达式相同的转义机制。
发布于 2020-11-15 21:33:00
如果应该按字面处理替换字符串,请使用Matcher.quoteReplacement
。它转义所有\
字符和$
字符。
String replacement= "a\\b"
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
https://stackoverflow.com/questions/27379046
复制相似问题