regex - grep的贪婪行为

标签 regex grep regex-greedy posix-ere

我认为在正则表达式中,“贪婪”适用于量词而不是整体匹配。然而,我观察到

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)? 匹配的相同位置开始的两个子字符串;这些是 aaaab .后者最长,因此匹配。

关于regex - grep的贪婪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59137763/

相关文章:

java - java中匹配转义序列的正则表达式

c# - 如何解析 HTML 节点的属性

ruby - gsub 的时间复杂度

bash - 使用 Perl 标志的 Grep 模式匹配最多 n 次

Javascript 贪婪的正则表达式似乎是非贪婪的

regex - sed 中的非贪婪(不情愿)正则表达式匹配?

java - Java正则表达式需要新鲜的眼光,这太贪婪了

java - 应该检查字符串的正则表达式是否包含指定的单词

regex - 如何正确运行find |与 grep + 转义字符并行?

linux - 继续用 bash grep 获取 traceroute 结果