【发布时间】:2018-05-24 03:30:55
【问题描述】:
我对正则表达式的最大重复次数有疑问:{n} 和 {n, m}。
$ man grep
...
Repetition
A regular expression may be followed by one of several repetition operators:
...
{n} The preceding item is matched exactly n times.
{n,} The preceding item is matched n or more times.
{,m} The preceding item is matched at most m times. This is a GNU extension.
{n,m} The preceding item is matched at least n times, but not more than m times.
...
现在考虑一个测试文件:
$ cat ./sample.txt
1
12
123
1234
然后将其 grep 为恰好重复 2 次的 [0-9](数字):
$ grep "[0-9]\{2\}" ./sample.txt
12
123
1234
?为什么会包括 123 和 1234?
另外,我在相同的文本文件中查找重复至少 2 次但不超过 3 次的数字:
$ grep "[0-9]\{2,3\}" ./sample.txt
12
123
1234
???为什么返回“1234”?
一个明显的解决方法是使用 grep 和 reverse-grep 过滤掉过多的结果。例如,
$ grep "[0-9]\{2,\}" ./sample.txt | grep -v "[0-9]\{4,\}"
12
123
谁能帮我理解为什么 {n} 返回包含重复 n 次的模式的行?为什么 {n,m} 会返回重复 m 次的模式??
【问题讨论】:
-
我认为所有 grep 所要做的就是在行中的某个地方找到它。它与额外的数字不匹配。