更优雅的正则表达式?可能有正面/负面的前瞻/落后? [英] A more elegant REGEX? Possibly with positive/negative lookaheads/behinds?

查看:30
本文介绍了更优雅的正则表达式?可能有正面/负面的前瞻/落后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一个正则表达式,它产生了预期的效果,但它有点笨重

I have a REGEX here which is producing the desired effect but it's a bit clunky

https://regex101.com/r/WwxW6G/2

\(.*?, USA\)|\(USA, .*?\)|\(.*?, USA, .*?\)

输入:

Match Me! (USA, Europe)
Match Me! (Europe, USA)
Match Me! (Asia, USA, Europe)

Don't Match Me (USA)
Don't Match Me USA
USA Don't Match Me
Don't Match Me (USA)

我想知道是否有办法在没有多个 OR 的情况下做到这一点 - 我不需要一个干净的括号来匹配,我只需要在检查中匹配正确的行.

I was wondering if there was a way to do this without several ORs - I don't need a clean bracket to be matched, I just need the right lines to be matched in a check.

非常感谢!

推荐答案

编辑 不是那么优雅,但我认为它是完整的 :S.

Edit It's not that elegant, but I think it's complete :S.

我要去;)

\((?=[^,)]*,)(?=(?:[^)]*, )?\bUSA\b(?=,|\)))(?:\w+,?\s*)+\)

它使用正向前瞻来确保括号内有一个逗号(所以它至少是两个词),以及词 USA(因为我猜这是一个要求 - 它没有说明在 Q).然后它只允许在括号内包含任意数量的逗号分隔的单词.

It uses positive lookaheads to ensure there's a comma inside the parentheses (so it's at least two words), as well as the word USA (because I'm guessing that's a requirement - it's not stated in the Q). Then it simply allows any number of comma separated words inside the parentheses.

这里是 regex101.

这篇关于更优雅的正则表达式?可能有正面/负面的前瞻/落后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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