gpt4 book ai didi

regex - 结合正则表达式?

转载 作者:行者123 更新时间:2023-12-03 05:51:44 24 4
gpt4 key购买 nike

收集用户针对各种条件的输入后,例如

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

如果用户输入多个条件,则创建单个正则表达式,我将它们与 "|" 结合起来,所以如果 1 和 2 给出它就变成 /(^@)|(@$)/

此方法到目前为止有效,但是,

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

<小时/>

Update: @(user input) won't be samefor two conditions and not all fourconditions always present but they canbe and in future I might need moreconditions like "is exactly" and "isexactly not" etc. so, I'm more curiousto know this approach will scale ?

Also there may be issues of user inputcleanup so regex escaped properly, butthat is ignored right now.

最佳答案

条件是 OR 运算还是 AND 运算在一起?

Starts with: abcEnds with: xyzContains: 123Doesn'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

关于regex - 结合正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/869809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com