【问题标题】:Regex to match two consecutive characters unless followed/preceded by more of the same character正则表达式匹配两个连续字符,除非后面/前面有更多相同的字符
【发布时间】:2017-08-22 21:28:01
【问题描述】:

我有一个如下所示的字符串:qqq Eqq Eqqq Cqq Eqq Fq。我想用h替换所有有两个连续字符的序列(在本例中为qq),所需的输出如下所示:qqq Eh Eqqq Ch Eh Fq

但是,我不希望正则表达式匹配超过两个 q 的序列(qqqqqqq)并使字符串看起来像这样:hq Eh Ehq Ch Eh Fq。我已经尝试了以下方法,但这会导致我不想要的输出。

text = "qqq Eqq Eqqq Cqq Eqq Fq";
text = text.replaceAll("[q]{2}", "h");

我也尝试只替换q's 后跟一个空格字符,但这只是匹配每个单词中的最后两个q's。有没有办法替换两个连续的字符,除非它们后面跟着同一个字符的第三个或第四个?如果有帮助,语言就是 Java。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    您可以使用基于环视的正则表达式:

    String text = "qqq Eqq Eqqq Cqq Eqq Fq";
    text = text.replaceAll("(?<!q)q{2}", "h");
    System.out.println(text);
    // => hq Eh Ehq Ch Eh Fq
    

    查看Java demoregex demo

    详情

    • (?&lt;!q) - 如果在当前位置的左侧紧邻 q,则匹配失败
    • q{2} - 2 q 字符。

    注意:如果您打算只替换 2 个未被 qs 包围的 q 字符,请在末尾添加一个负前瞻 (?!q)"(?&lt;!q)q{2}(?!q)"

    【讨论】:

      【解决方案2】:

      如果你想匹配任何字符,而不是特定字符,你必须使用相当复杂的东西,因为 Java 的正则表达式不支持 variable-length look-behinds。我想出了这个:

      (?!([a-z])\1\1)(.)([a-z])\3(?!\3)
      

      说明:

      (?!            # negative look-ahead
        ([a-z])\1\1  # [group 1] match a letter and 2 more of the same letter
      )              # end of the negative look-ahead
      (.)            # [group 2] match any character - this is for some other character 
                     # before what you want ('E', 'C', or 'F' in your examples)
                     # this will not match the repeated character -
                     # guaranteed by the previous negative look-ahead
      ([a-z])        # [group 3] the letter to be replaced
      \3             # the same letter (reference to the previous group)
      (?!\3)         # negative look-ahead - 
                     # makes the pattern not match more than 2 of the same character
      

      你必须用$2h替换($2在模式中是(.)

      Java demo, regex101 demo

      【讨论】:

        猜你喜欢
        • 2012-02-11
        • 1970-01-01
        • 2017-05-09
        • 2021-04-16
        • 2015-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多