Java 如何用正则表达式替换最后一个字符为特殊字符的单词

Java 如何用正则表达式替换最后一个字符为特殊字符的单词,java,regex,Java,Regex,这是我的密码 String textContent = "L.A. is best place"; String reg = "L.A."; reg = reg.replaceAll("\\.","\\\\."); String regex ="\\s*\\b" + reg + "\\b\\s*"; pat = Pattern.compile(regex,Pattern.CASE_INSENSITIVE); mat = pat.matcher(textContent); textConten

这是我的密码

String textContent = "L.A. is best place";
String reg = "L.A.";
reg = reg.replaceAll("\\.","\\\\.");

String regex ="\\s*\\b" + reg + "\\b\\s*";

pat = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
mat = pat.matcher(textContent);
textContent = mat.replaceAll(" (Name) ");
我希望最后的文本内容是(名字)是最好的地方。但事实并非如此。 但是如果String reg=“L.A”。最后的文本内容是(名称)。这是最好的地方


谢谢。

试试这个正则表达式

String s = "L.A. is best place";
String replaced = s.replaceAll("(?i)\\b[a-z.]+[*+.$()\\[\\]]", "(Name)");
System.out.println(replaced);
输出:

(Name) is best place

我想你想要
reg=Pattern.quote(reg)