当模式(不)包含带括号的组时,为什么expr匹配输出不同的东西?

时间:2011-06-26 21:48:21

标签: regex linux bash pattern-matching

为什么

$ echo `expr match abcdef 'abc'`

给出匹配的字符数,即3,但

$ echo `expr match abcdef '\(abc\)'`

给出匹配的字符,即abc?

我理解正则表达式匹配在这里发挥作用,但无法理解括号中的子表达式如何在这里产生这种差异?

2 个答案:

答案 0 :(得分:7)

这是来自expr:

的手册页

Pattern matches return the string matched between \( and \) or null; if \( and \) are not used, they return the number of characters matched or 0.

Man page.

答案 1 :(得分:2)

这与正则表达式无关。命令“expr”的工作原理只是一个区别。第一个返回匹配子字符串的长度,第二个返回匹配的子字符串本身。

有一个非常好的总结:TLDP refcard。您可以找到组合的摘要,如何使用expr。