将整个单词与前导或尾随特殊符号(如字符串中的美元)匹配

问题描述 投票:7回答:4

我可以使用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?

java regex replaceall
4个回答
4
投票

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

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

regex demo

(?<!\w)是一个负面的lookbehind,如果在当前位置的左边有一个非单词char并且(?!\w)是一个负面的前瞻,如果在右边有一个非单词char,则会失败。当前位置。 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

1
投票

Matcher.quoteReplacement()用于替换字符串(to),而不是正则表达式(from)。要在正则表达式中包含字符串文字,请使用Pattern.quote()

from = Pattern.quote(from);

1
投票

$在正则表达式中具有特殊含义(意思是“输入结束”)。要从目标中的字符中删除任何特殊含义,请将其包装在正则表达式引号/非引号表达式\Q...\E中。此外,因为$不是“单词”字符,所以单词边界不会wiork,所以请使用环顾四周:

line = line.replaceAll("(?<!\\S)\\Q" + from + "\\E(?![^ ,])", to);

0
投票

通常,Pattern.quote是逃避可能由正则表达式引擎特别解释的字符的方法。

但是,正则表达式仍然不正确,因为在$line之前没有单词边界; space和$都是非单词字符。您需要在$字符后面放置单词边界。这里没有Pattern.quote,因为你自己逃避了。

String from = "\\$\\btemp4\\b";

或者更简单地说,因为你知道$temp4之间已有一个单词边界:

String from = "\\$temp4\\b";

from变量可以从要替换的表达式构造。如果from"$temp4",那么你可以逃脱美元符号并添加一个单词边界。

from = "\\" + from + "\\b";

输出:

add, register1, $temp40, 42
© www.soinside.com 2019 - 2024. All rights reserved.