试图获取连续重复字母出现两次或三次的单词。无法找到使用 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
相关搜索链接,我查了一些,但没有得到任何接近这个问题的东西
如果这在较新版本的
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/