这是我的代码
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".最终的文本内容是 (Name) 。是最好的地方。
谢谢。
最佳答案
尝试一下这个正则表达式,
String s = "L.A. is best place";
String replaced = s.replaceAll("(?i)\\b[a-z.]+[*+.$()\\[\\]]", "(Name)");
System.out.println(replaced);
输出:
(Name) is best place
关于java - 如何用正则表达式替换最后一个字符为特殊字符的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319334/