AND/OR 运算符在正则表达式中如何表示?
我目前正在编写一个词汇算法来检查用户是否正确输入了单词。我有以下情况: 该词的正确答案是“part1,part2”。 用户应该能够输入“part1”(答案 1)、“part2”(答案 2)或“part1,part2”(答案 3)。 我现在尝试将用户给出的字符串与以下自动创建的正则表达式进行匹配:
^(part1|part2)$
这只返回正确的答案 1 和 2,而答案 3 是错误的。我现在想知道是否有类似于 | 的运算符上面写的是and/or
,而不是either...or
。
有人可以帮我解决这个问题吗?
I'm currently programming a vocabulary algorithm that checks if a user has typed in the word correctly. I have the following situation:
The correct solution for the word would be "part1, part2".
The user should be able to enter either "part1" (answer 1), "part2" (answer 2) or "part1, part2" (answer 3).
I now try to match the string given by the user with the following, automatically created, regex expression:
^(part1|part2)$
This only returns answer 1 and 2 as correct while answer 3 would be wrong. I'm now wondering whether there's an operator similar to | that says and/or
instead of either...or
.
May anyone help me solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我假设您想要动态构建一个正则表达式来包含第 1 部分和第 2 部分之外的其他单词,并且您希望顺序无关紧要。如果是这样,您可以使用如下内容:
正匹配:
负匹配:
I'm going to assume you want to build a the regex dynamically to contain other words than part1 and part2, and that you want order not to matter. If so you can use something like this:
Positive matches:
Negative matches:
有效吗?
does it work?
不是正则表达式专家,但您可以执行
^((part1|part2)|(part1,part2))$
。换句话说:“第 1 部分或第 2 部分或两者”Not an expert in regex, but you can do
^((part1|part2)|(part1, part2))$
. In words: "part 1 or part2 or both"这个不用交替就可以工作吗?
或者为什么不呢?
第一个适用于所有条件,第二个适用于除
part2
之外的所有条件(使用 GNU sed 4.1.5)Does this work without alternation?
or why not this?
The first works for all conditions the second for all but
part2
(using GNU sed 4.1.5)或者你可以使用这个:
Or you can use this: