通过正则表达式查找括号 [英] Finding parenthesis via regular expression

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

问题描述

我不擅长正则表达式.我正在寻找一个字符串是否包含( ),[ ], { }".注意,我不是在实际中寻找 ( ) 中的内容,只是为了查看字符串是否包含 ( ) 或 { }, [ ].

I am not great with regular expressions. I am looking to find if a string contains "( ),[ ], { }". Note, I am not looking for the contents in the actual ( ), just to see if the string contains ( ) or { }, [ ].

我知道如果我执行 .scan,它将获取任何匹配项并创建一个数组(我想要的).我只是不知道表达方式.

I know if I do .scan, it will take any matches and create an array (which I want). I just don't know the expression.

推荐答案

使用非贪婪匹配的替代方案:

Use alternatives with a non-greedy match:

/\(.*?\)|\{.*?\}|\[.*?\]/

如果没有这些问号,模式 .* 将是贪婪的",例如扫描abc(def)ehi(jkl)mno"只会找到一个匹配的(def)ehi(jkl)"(.* 会将所有内容吞噬到最后一个右括号),但是使用非贪婪的 .*? 你会得到两个匹配(def)"和(jkl)",如您所愿.

Without those question marks, the patterns .* would be "greedy", eg scanning "abc(def)ehi(jkl)mno" would find only one match of "(def)ehi(jkl)" (the .* would gobble up everything to the last close bracket), but using non-greedy .*? you would get two matches "(def)" and "(jkl)" as you would want.

这篇关于通过正则表达式查找括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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