除了匹配的第一个字母外,还可以在正则表达式中捕获重复的字母

我正在尝试获取一个正则表达式,该正则表达式可以捕获重复的字母,但第一个匹配的字母除外。

我有一个可获取重复字母的正则表达式:([a-z])\ 1 {2,}

但是,这会在sooo中捕获“ ooo”。但是我只想捕捉“ oo”

(将此用于Google表格中的查找和替换功能)

评论
失忆症
失忆症

由于您没有提到您使用的是哪种编程语言或正则表达式,因此我将提供多种选择:

  1. Use a capturing group:

    ([a-z])(\1{2,})
    

    Demo.

    This will work with every regex flavor but your expected match would be in the second capturing group.

  2. If your regex flavor supports Lookarounds, use a positive Lookbehind:

    (?<=([a-z]))\1{2,}
    

    Demo.

  3. If your regex flavor supports \K, you can use the following:

    ([a-z])\K\1{2,}
    

    Demo.

Note that \1{2,} means that you'll have a match only if the letter is repeated at least 3 times (e.g., aaa). If that's not what you intended and you want to have a match when the letter is repeated twice, you should use \1+ instead.

点赞
评论