正则表达式:{n}和{n,m}忽略最大重复次数

Cul*_*lip 2 regex grep

我对正则表达式的最大重复次数有疑问:{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.
...
Run Code Online (Sandbox Code Playgroud)

现在考虑一个测试文件:

$ cat ./sample.txt
1
12
123
1234
Run Code Online (Sandbox Code Playgroud)

然后将其重复[0-9](数字),精确重复2次:

$ grep "[0-9]\{2\}" ./sample.txt
12
123
1234
Run Code Online (Sandbox Code Playgroud)

?为什么这包括123和1234?

另外,我将相同的文本文件grep重复至少2次但不超过3次的数字:

$ grep "[0-9]\{2,3\}" ./sample.txt
12
123
1234
Run Code Online (Sandbox Code Playgroud)

??? 为什么返回“ 1234”?

一个明显的解决方法是使用grep和reverse-grep过滤掉过多的结果。例如,

$ grep "[0-9]\{2,\}" ./sample.txt | grep -v "[0-9]\{4,\}"
12
123
Run Code Online (Sandbox Code Playgroud)

谁能帮助我理解为什么{n}返回包含重复n次的模式的行?为什么{n,m}返回重复m次的模式?

Zak*_*Zak 5

除非您锚定正则表达式,否则它们可以匹配字符串中的任何位置。

$ grep "[0-9]\{2\}" ./sample.txt 将匹配任何包含2位数字的行。

使用^强迫你的表情,开始在一行的开头,并$迫使它匹配到行的末尾。例如。

$ grep '^[0-9]\{2\}$' ./sample.txt
# Using single quotes to avoid potential substitution issues. Hat tip to @ghoti
Run Code Online (Sandbox Code Playgroud)

这只能返回12