RegExp - 替换确切的字符串

RegExp - Replace exact String

我需要正则表达式方面的帮助,我正在尝试将许多字符串的 "Inc" 替换为 "LLC"。

我在 java 中使用了这段代码:

String newValue = newValue.replaceAll("(?i)Inc[^\w]","LLC");

但是结果不对,替换后去掉了一个字符:

Exp: CONSULTANTS, INC. ("ABC") ==> CONSULTANTS, LLC ("ABC") // "."已删除。

请注意,我已使用 [^\w] 来防止在 "include".

等句子中替换 "inc"

如果字符串中没有像 ^() 这样的特殊文字,您可以将 \b 用于 word boundaries

String s = "include inc".replaceAll("(?i)\binc\b", "LLC");
System.out.println(s); // (?i) is for case insensitive.

如果您使用特殊字符代替 inc,如 ^inc,上述方法将失败。您可以使用 Pattern.quote(s) 让它工作。

如果有特殊字符,则可以使用带引号的文字\Q...\E。使用引用文字的实用方法:

public static String replaceExact(String str, String from, String to) {
    return str.replaceAll("(?<!\w)\Q" + from + "\E(?!\w)", to);
}

注意:Pattern.quote("wor^d") 将 return \Qwor^d\E 与上面的正则表达式相同。