【问题标题】:Java: replace character inside a matching regexJava:替换匹配的正则表达式中的字符
【发布时间】:2014-10-22 08:22:34
【问题描述】:

我有一个字符串。假设:
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:

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

【问题讨论】:

  • 你的预期输出是什么?

标签: java regex replace pattern-matching


【解决方案1】:

您可以考虑使用 Positive Lookahead 来断言后面是字母、点 . 或空格。

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..."

【讨论】:

  • 我认为“Z”后面的点需要两个反斜杠。 1 美元是什么意思?
  • $1 从组索引 1 反向引用匹配结果。
【解决方案2】:

您可以使用下面的正则表达式,它使用正向向后查找来删除所有出现在大写字母之后的点,

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】:
    (?<=[A-Z])(\.)(?=[A-Z]|\.|\s)
    

    你可以试试这个。

    查看演示。

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

    【讨论】:

      【解决方案4】:

      为此使用“环视”。 下面的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...
      

      【讨论】:

        猜你喜欢
        • 2015-01-04
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        • 1970-01-01
        • 2022-12-01
        • 2013-01-18
        • 2019-10-20
        • 1970-01-01
        相关资源
        最近更新 更多