结合正则表达式? [英] Combine Regexp?

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

问题描述

收集用户输入的各种条件后

After collecting user input for various conditions like

  1. 以:/(^@)/
  2. 开头
  3. 以:/(@$)/
  4. 结尾
  5. 包含:/@/
  6. 不包含

如果用户输入多个条件,则生成单个正则表达式,我将它们与 "|" 结合,所以如果 1 和 2 给定它成为 /(^@)|(@$)/

To make single regex if user enter multiple conditions, I combine them with "|" so if 1 and 2 given it become /(^@)|(@$)/

这个方法目前有效,但是,

This method works so far but,

我无法正确确定,第四个条件的正则表达式应该是什么?并以这种方式结合正则表达式是否有效?

I'm not able to determine correctly, What should be the regex for the 4th condition? And combining regex this way work?

更新:@(user input) 不一样了对于两个条件而不是所有四个条件条件总是存在,但他们可以是和将来我可能需要更多像正是"这样的条件和是完全不是"等所以,我更好奇知道这种方法会扩展吗?

Update: @(user input) won't be same for two conditions and not all four conditions always present but they can be and in future I might need more conditions like "is exactly" and "is exactly not" etc. so, I'm more curious to know this approach will scale ?

也可能存在用户输入的问题清理使正则表达式正确转义,但是现在被忽略了.

Also there may be issues of user input cleanup so regex escaped properly, but that is ignored right now.

推荐答案

条件是 ORed 还是 ANDed 在一起?

Will the conditions be ORed or ANDed together?

Starts with: abc
Ends with: xyz
Contains: 123
Doesn't contain: 456

OR 版本相当简单;正如您所说,这主要是在各个条件之间插入管道的问题.只要其中一个选项匹配,正则表达式就会停止寻找匹配项.

The OR version is fairly simple; as you said, it's mostly a matter of inserting pipes between individual conditions. The regex simply stops looking for a match as soon as one of the alternatives matches.

/^abc|xyz$|123|^(?:(?!456).)*$/

第四种选择可能看起来很奇怪,但这就是您在正则表达式中表达不包含"的方式.顺便说一下,备选方案的顺序并不重要;这实际上是相同的正则表达式:

That fourth alternative may look bizarre, but that's how you express "doesn't contain" in a regex. By the way, the order of the alternatives doesn't matter; this is effectively the same regex:

/xyz$|^(?:(?!456).)*$|123|^abc/

AND 版本更复杂.在每个单独的正则表达式匹配后,匹配位置必须重置为零,以便下一个正则表达式可以访问整个输入.这意味着所有条件都必须表示为前瞻(从技术上讲,其中之一不必是前瞻,我认为这样可以更清楚地表达意图).最后的 .*$ 完成匹配.

The AND version is more complicated. After each individual regex matches, the match position has to be reset to zero so the next regex has access to the whole input. That means all of the conditions have to be expressed as lookaheads (technically, one of them doesn't have to be a lookahead, I think it expresses the intent more clearly this way). A final .*$ consummates the match.

/^(?=^abc)(?=.*xyz$)(?=.*123)(?=^(?:(?!456).)*$).*$/

然后还有组合 AND 和 OR 条件的可能性——这就是真正有趣的开始.:D

And then there's the possibility of combined AND and OR conditions--that's where the real fun starts. :D

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

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