简体   繁体   English

正则表达式在sed中不匹配

[英]Regex not matching in sed

I have used regexs for years, and never come across this problem. 我已经使用了多年的正则表达式,从来没有遇到过这个问题。 On example websites (like http://regexone.com/lesson/1 ) where I can play around with what I'm trying to do, it matches, but in the unix shell using sed , it doesn't match. 在示例网站(如http://regexone.com/lesson/1 )上,我可以玩我正在尝试做的事情,它匹配,但在使用sed的unix shell中,它不匹配。 I discovered this when trying to write logcheck skipping rules. 我在尝试编写logcheck跳过规则时发现了这一点。

$ echo 'Hello, world!' | sed '/^\w\w\wlo, wor.*$/d'
$

Works, but 工作,但是

$ echo 'Hello, world!' | sed '/^\w{3}lo, wor.*$/d'
Hello, world!

doesn't. 没有。 It doesn't see 3 alphanums with the {3} it seems. 它似乎没有看到{3}的3个alphanums。

I found this out by trying to do reductions on 我试图通过减少来发现这一点

$ echo "Jul 15 11:31:08 gateway-laptop dbus[3076]: [system] Successfully activated service 'org.freedesktop.PackageKit'"|sed "/^\w{3} [ :0-9]{11} [._[:alnum:]-]+ dbus\[[0-9]+\]: \[system\].*/d"
Jul 15 11:31:08 gateway-laptop dbus[3076]: [system] Successfully activated service 'org.freedesktop.PackageKit'

Which I would have thought should match. 我认为应该匹配。 Reducing this complexity, this doesn't match 降低这种复杂性,这是不匹配的

$ echo "Jul 15 11:31:08 gateway-laptop dbus[3076]: [system] Successfully activated service 'org.freedesktop.PackageKit'"|sed "/^\w{3}.*"/d
Jul 15 11:31:08 gateway-laptop dbus[3076]: [system] Successfully activated service 'org.freedesktop.PackageKit'

It looks like its behavior ^\\w{3} should match the first 3 alphanumeric characters in the line, then the .* should match the rest of the line to the EOL. 看起来它的行为^ \\ w {3}应该与行中的前3个字母数字字符匹配,然后。*应该与行的其余部分匹配到EOL。

Escape the braces otherwise sed's default behavior is to match {} or () literally: 逃避大括号否则sed的默认行为是按字面顺序匹配{} or ()

echo 'Hello, world!' | gsed '/^\w\{3\}lo, wor.*$/d'

Or else you need -r flag for extended regex capabilities: 否则你需要-r标志来扩展正则表达式功能:

echo 'Hello, world!' | gsed -r '/^\w{3}lo, wor.*$/d'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM