使用egrep匹配包含3个重复数字的行,不一定是连续的,即“3 33”,“55 5”,“666”或“a6b6c6d”。我有一个初步想法。
我试过了:
egrep '1[^1]*1[^1]*1' test
这将识别像1abd1df31这样的东西。 但是,我尽量不要枚举从0到9的所有数字。那么如何使用反向引用来概括它呢?
提前致谢!
注意:这三位数应该相同。即。 3aa2aa1aa不应该匹配。
答案 0 :(得分:0)
这适用于简单的情况:
egrep '^[^0-9]*([0-9])[^0-9]*\1[^0-9]*\1[^0-9]*$'
说明:
[^0-9]*
零或多个非数字([0-9])
一个用parens捕获的数字\1
对已捕获数字的反向引用[^0-9]
零个或多个无数字^
和$
行的开头和结尾警告计划:
匹配3 foo 3 bar 3
但3 4 3 baz 3
失败。换句话说,该行中不允许使用其他数字,只需要您正在寻找的数字。
尝试使用Perl单行程序来匹配多种数字类型的棘手案例。
perl -ne '$i=$_;%a=();$a{$_}++for(split//,$i);for(0..9){if($a{$_}==3){print $i;last}}'
对于每一行$i
,它会创建一个由行的每个字符寻址的散列%a
,存储出现次数。然后我检查出现次数为3的数字,如果找到,则打印行$i
。
答案 1 :(得分:0)
这样做:
/(?=.*?(\d))(?:(?:.*?\1){3})/
<强>说明强>
(?=.*?(\d))(?:(?:.*?\1){3})
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=.*?(\d))»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the regular expression below and capture its match into backreference number 1 «(\d)»
Match a single digit 0..9 «\d»
Match the regular expression below «(?:(?:.*?\1){3})»
Match the regular expression below «(?:.*?\1){3}»
Exactly 3 times «{3}»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the same text as most recently matched by capturing group number 1 «\1»