我认为在正则表达式中,“贪婪”适用于量词而不是整体匹配。然而,我观察到
grep -E --color=auto 'a+(ab)?' <(printf "aab")
返回 aab 而不是 aab。
这同样适用于 sed。
另一方面,在pcregrep等工具中,贪婪的其实是量词。
这是grep的特定行为吗?
注意我检查了两个
grep (BSD grep) 2.5.1-FreeBSD 和 grep (GNU grep) 3.1
最佳答案
在 the description of term matched , POSIX 指出
The search for a matching sequence starts at the beginning of a string and stops when the first sequence matching the expression is found, where "first" is defined to mean "begins earliest in the string". If the pattern permits a variable number of matching characters and thus there is more than one such sequence starting at that point, the longest such sequence is matched.
这个陈述清楚地回答了你的问题。字符串
aab
包含从与 ERE a+(ab)?
匹配的相同位置开始的两个子字符串;这些是 aa
和 aab
.后者最长,因此匹配。
关于regex - grep的贪婪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59137763/