regex - ERE - 将量词添加到具有内部组和反向引用的组

标签 regex sed grep gnu pcre

试图获取连续重复字母出现两次或三次的单词。无法找到使用 ERE 使用量词和捕获组的方法

$ grep --version | head -n1
grep (GNU grep) 2.25

$ # consecutive repeated letters occurring twice
$ grep -m5 -xiE '[a-z]*([a-z])\1[a-z]*[a-z]*([a-z])\2[a-z]*' /usr/share/dict/words
Abbott
Annabelle
Annette
Appaloosa
Appleseed

$ # no output for this, why?
$ grep -m5 -xiE '([a-z]*([a-z])\2[a-z]*){2}' /usr/share/dict/words

-P 一起使用尽管
$ grep -m5 -xiP '([a-z]*([a-z])\2[a-z]*){2}' /usr/share/dict/words
Abbott
Annabelle
Annette
Appaloosa
Appleseed

$ grep -m5 -xiP '([a-z]*([a-z])\2[a-z]*){3}' /usr/share/dict/words
Chattahoochee
McConnell
Mississippi
Mississippian
Mississippians

感谢 Casimir et Hippolyte想出更简单的输入和正则表达式来测试这种行为
$ echo 'aazbb' | grep -E '(([a-z])\2[a-z]*){2}' || echo 'No match'
aazbb
$ echo 'aazbbycc' | grep -E '(([a-z])\2[a-z]*){2}([a-z])\3[a-z]*' || echo 'No match'
aazbbycc
$ echo 'aazbbycc' | grep -P '(([a-z])\2[a-z]*){3}' || echo 'No match'
aazbbycc

$ # failing case
$ echo 'aazbbycc' | grep -E '(([a-z])\2[a-z]*){3}' || echo 'No match'
No match

sed 相同的行为还有
$ sed --version | head -n1
sed (GNU sed) 4.2.2

$ echo 'aazbb' | sed -E '/(([a-z])\2[a-z]*){2}/! s/.*/No match/'
aazbb    
$ echo 'aazbbycc' | sed -E '/(([a-z])\2[a-z]*){2}([a-z])\3[a-z]*/! s/.*/No match/'
aazbbycc

$ # failing case
$ echo 'aazbbycc' | sed -E '/(([a-z])\2[a-z]*){3}/! s/.*/No match/'
No match

相关搜索链接,我查了一些,但没有得到任何接近这个问题的东西
  • https://savannah.gnu.org/bugs/?group=grep
  • http://lists.gnu.org/archive/html/bug-sed/

  • 如果这在较新版本的 grep 中得到解决或 sed , 让我知道。此外,如果在非 GNU 实现中发现问题

    最佳答案

    我想 -E不允许 Quantifiers ,这就是为什么它只适用于 -P
    匹配 2 个或多个连续的重复字母组:

    grep -P '(?:([a-z])\1*([a-z])\2){1}' /usr/share/dict/words
    

    匹配 3 个或更多连续的重复字母组:
    grep -P '(?:([a-z])\1*([a-z])\2){2}' /usr/share/dict/words
    

    选项:
    -P, --perl-regexp         PATTERN is a Perl regular expression
    

    关于regex - ERE - 将量词添加到具有内部组和反向引用的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572924/

    相关文章:

    bash - shell脚本解析日志文件

    javascript - 正则表达式:通过前瞻添加否定案例

    c# - 16 位数字的基本正则表达式

    ruby - 使用特定规则拆分字符串的最干净的 ruby​​ 代码

    mysql - 在 MySQL 中使用正则表达式。它会给出出现次数吗?

    bash - 在 Bash 中删除空行并修剪周围的空格

    bash - 如何循环处理每个输出行?

    regex - 使用sed删除不匹配的部分

    sed 失败并出现 "unknown option to ` s'"错误

    ubuntu - Windows 10 Ubuntu WSL 无法显示 grep 输出文件名