sed-Linux中的正则表达式方括号检测 [英] sed - regex square brackets detection in Linux

查看:62
本文介绍了sed-Linux中的正则表达式方括号检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ubuntu 14.04,并且具有以下语句:

I am using Ubuntu 14.04, and I have the following statement:

192.168.2.4 [text to capture] Test: This is a test statement.

我正在尝试使用以下正则表达式捕获要捕获的文本":

I am trying to capture "text to capture" using the following regex:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^\[\]]*\[(.*)\].*$/\1/"

regex的思想是遍历所有与左,右方括号都不匹配的字符.一旦遇到方括号,请捕获文本直到遇到方括号,然后忽略所有后续字符.

The idea behind the regex is to traverse over all characters which do not match opening and closing square bracket. Once an opening square bracket is encountered, capture the text until the closing bracket is encountered, then ignore all subsequent characters.

当我在 regex测试器中使用上述正则表达式时,我可以看到要捕获的文本"被捕获.

When I use the regex above in a regex tester, I can see that the "text to capture" is being captured.

但是,执行上面的regex命令会返回完整的语句,又称:

However, executing the regex command above returns the complete statement aka:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^\[\]]*\[(.*)\].*$/\1/"

有人可以在这里发现我错过的内容吗?我相信我已经正确地逃脱了括号,因为它可以与正则表达式测试器一起正常工作.

Can anyone spot what I have missed here? I believe I have escaped the characters brackets correctly, since it is working correctly with the regex tester.

谢谢约翰

推荐答案

实际上,您只需要在第一条语句中排除起始 []:

You actually need to exclude only for the starting [ in the first statement:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
sed -r "s/^[^[]*\[(.*)\].*$/\1/"

如果您确实希望在 [^] 中同时包含 [] ,只需使用 [^] [] 并且您不需要转义.

If you really want both [ and ] inside a [^ ] just use [^][] and you don't need escaping.

这篇关于sed-Linux中的正则表达式方括号检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆