Grep正则表达式捕获问题

时间:2017-07-13 20:29:32

标签: regex grep

为什么这与捕获组不匹配?

grep -rPo 'ServerMethod\(me\.[a-zA-Z]*\.([a-zA-Z]*)\)'

它返回:

test.js:ServerMethod(me.obProcedures.SaveProcess)    
test.js:ServerMethod(me.obProcedures.Commit)

但我需要:

SaveProcess            
Commit

cygwin版本: 2.5.2(0.297 / 5/3)

1 个答案:

答案 0 :(得分:2)

之所以如此,是因为grep没有返回捕获组内容,只返回整个匹配。

您可以使用\K匹配重置运算符和正向前瞻:

grep -Po 'ServerMethod\(me\.[a-zA-Z]*\.\K[a-zA-Z]+(?=\))'

请参阅online demo

<强>详情:

  • ServerMethod\(me\. - 匹配文字字符串ServerMethod(me.
  • [a-zA-Z]* - 0个或更多ASCII字母
  • \. - 一个文字点
  • \K - 省略匹配到目前为止匹配的文字
  • [a-zA-Z]+ - 一个或多个ASCII字母
  • (?=\)) - 一个积极的前瞻,需要在当前位置右侧立即),但不会将其添加到匹配项中(因为它是非消费 pattern)。

或者,由于PCRE grep选项并非始终可用,请将sedgrep一起使用:

grep 'ServerMethod(me\.' | sed 's/.*ServerMethod(me\.[a-zA-Z]*\.\([a-zA-Z]*\)).*/\1/'

请参阅another demo

此处,模式符合POSIX BRE:

  • ServerMethod(me\. - 匹配文字ServerMethod(me.文字,grep获取带有此文字的行
  • .*ServerMethod(me\.[a-zA-Z]*\.\([a-zA-Z]*\)).* - 匹配有一条​​线
    • .* - 尽可能多的0个字符
    • ServerMethod(me\. - 文字ServerMethod(me.文字
    • [a-zA-Z]* - 0+ ASCII字母
    • \. - 一个文字点
    • \([a-zA-Z]*\) - 捕获第1组(通过\1引用):0+ ASCII字母
    • ) - 文字)
    • .* - 尽可能多的0个字符