收集用户针对各种条件的输入后,例如
- 开头为:
/(^@)/
- 结尾为:
/(@$)/
- 包含:
/@/
- 不包含
如果用户输入多个条件,则创建单个正则表达式, 我将它们与 "|"
结合起来,所以如果 1 和 2 给出它就变成 /(^@)|(@$)/
此方法到目前为止有效,但是,
我无法正确确定,第四个条件的正则表达式应该是什么?并以这种方式组合正则表达式?
<小时 />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.
请您参考如下方法:
条件是 OR 运算还是 AND 运算在一起?
Starts with: abc Ends with: xyz Contains: 123 Doesn't contain: 456
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).)*$/
第四种选择可能看起来很奇怪,但这就是您在正则表达式中表达“不包含”的方式。顺便说一句,选项的顺序并不重要;这实际上是相同的正则表达式:
/xyz$|^(?:(?!456).)*$|123|^abc/
AND 版本更复杂。每个单独的正则表达式匹配后,匹配位置必须重置为零,以便下一个正则表达式可以访问整个输入。这意味着所有条件都必须表示为前瞻(从技术上讲,其中一个条件不必是前瞻,我认为这样可以更清楚地表达意图)。最后的 .*$
使比赛圆满结束。
/^(?=^abc)(?=.*xyz$)(?=.*123)(?=^(?:(?!456).)*$).*$/
然后还有组合 AND 和 OR 条件的可能性 - 这就是真正的乐趣开始的地方。 :D