基本正则表达式与扩展正则表达式中 * 的含义

基本正则表达式与扩展正则表达式中 * 的含义

我认为 * 表示在基本或扩展正则表达式中位于其前面的零个或多个字符或类。为什么echo hello| grep '*llo'失败但echo hello |egrep '*llo'成功?

答案1

当使用 grep/egrep/fgrep 时,您可以包含标志-o以使 grep 仅返回匹配的字符。(如果您有一个漂亮的彩色终端,您也可以尝试--color让它突出显示返回行中的匹配项。它通常在这种情况下有所帮助。

echo "that star " | grep -o '*count'
echo "that star " | egrep -o '*count'
echo "that star " | fgrep -o '*count'
echo "that star counted" | grep -o '*count'
echo "that star counted" | egrep -o '*count'  ## returns "count"
echo "that star counted" | fgrep -o '*count'
echo "that star *counted" | grep -o '*count'  ## returns "*count"
echo "that star *counted" | egrep -o '*count'  ## returns "count"
echo "that star *counted" | fgrep -o '*count'  ## returns "*count"

没有评论的则没有返回任何内容。

因此,区别在于,当旧的 grep 和 fgrep 解析器没有看到星号前的字符或集合时,它们会选择将其作为普通字符进行匹配。egrep 将其视为无操作或无效,并默默继续。

(还有一点,我有时使用 pcregrep 来实现 perl 正则表达式兼容性,当正则表达式以星号开头时,它实际上会抛出一条错误消息!)

答案2

http://www.regular-expressions.info/repeat.html

http://www.robelle.com/smugbook/regexpr.html

在正则表达式中,星号用于查找其前面的字符的模式,而不是其前面的字符。

换句话说,您应该说echo hello | grep 'llo*'查找“llo”或“lloooo”等以匹配模式中的更多字母,并用括号将其括起来。 (llo)* 将找到 llo、llollo 等。

我猜测带有 * 的 grep 会失败,因为它不是一个有效的正则表达式,而 egrep 只是忽略了 *。

相关内容