Java:替换匹配的正则表达式中的字符

时间:2014-08-28 12:55:45

标签: java regex replace pattern-matching

我有一个字符串。让我们说:
String s = "This is my P.C.. My P.C. is the best.O.M.G!! Check this...";

我想将所有P.C.替换为PC字,将O.M.G替换为OMG。一般来说,我想要替换单个字母或单个字母和空格或点之间的所有点。我认为匹配的正则表达式是:

[^A-Za-z][A-Za-z]\\.[A-Za-z\\s\\.][^A-Za-z]

如何只替换那里的点而不是匹配的所有内容?

修改

预期产出:

"This is my PC. My PC is the best.OMG!! Check this..."

EDIT2:

基本任务是从可以用或不用点写入的缩写和首字母缩写词中删除点。所以一个好的正则表达式也是有价值的

4 个答案:

答案 0 :(得分:2)

您可以考虑使用正向前瞻来断言后面的字母是点,点.还是空格。

String s = "This is my P.C.. My P.C. is the best.O.M.G!! Check this...";
String r = s.replaceAll("([A-Z])\\.(?=[ A-Z.])", "$1");
System.out.println(r); //=> "This is my PC. My PC is the best.OMG!! Check this..."

答案 1 :(得分:0)

使用" lookarounds"为了这。 如果之后是大写字母,则下面的Pattern会替换点

如果您挑剔并希望将..清理为.而不影响暂停...,则建议进行第二次迭代。

String s = "This is my P.C.. My P.C. is the best.O.M.G!! Check this...";
//                               | preceded by capital letter
//                               |         | escaped dot
//                               |         |  | followed by capital letter
//                               |         |  |           | replace with empty String
System.out.println(s.replaceAll("(?<=[A-Z])\\.(?=[A-Z])", "")
    // second replacement: ".." folllowed by whitespace is "sanitized" with only 1 dot
    .replaceAll("\\.{2}(?=\\s)", "."));

<强>输出

This is my PC. My PC. is the best.OMG!! Check this...

答案 2 :(得分:0)

您可以使用以下正则表达式使用正向lookbehind来删除大写字母后面的所有点,

System.out.println("This is my P.C.. My P.C. is the best.O.M.G!! Check this...".replaceAll("(?<=[A-Z])\\.", ""));

<强>输出:

This is my PC. My PC is the best.OMG!! Check this...

答案 3 :(得分:0)

(?<=[A-Z])(\.)(?=[A-Z]|\.|\s)

你可以试试这个。

参见演示。

http://regex101.com/r/lK9iD2/2