AND/OR 运算符在正则表达式中如何表示?

发布于 2024-12-14 03:32:20 字数 329 浏览 2 评论 0原文

我目前正在编写一个词汇算法来检查用户是否正确输入了单词。我有以下情况: 该词的正确答案是“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

机场等船 2024-12-21 03:32:20

我假设您想要动态构建一个正则表达式来包含第 1 部分和第 2 部分之外的其他单词,并且您希望顺序无关紧要。如果是这样,您可以使用如下内容:

((^|, )(part1|part2|part3))+$

正匹配:

part1
part2, part1
part1, part2, part3

负匹配:

part1,           //with and without trailing spaces.
part3, part2, 
otherpart1

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:

((^|, )(part1|part2|part3))+$

Positive matches:

part1
part2, part1
part1, part2, part3

Negative matches:

part1,           //with and without trailing spaces.
part3, part2, 
otherpart1
意中人 2024-12-21 03:32:20
'^(part1|part2|part1,part2)

有效吗?

有效吗?

'^(part1|part2|part1,part2)

does it work?

does it work?

别闹i 2024-12-21 03:32:20

不是正则表达式专家,但您可以执行^((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"

野生奥特曼 2024-12-21 03:32:20

这个不用交替就可以工作吗?

^((part)1(, \22)?)?(part2)?$

或者为什么不呢?

^((part)1(, (\22))?)?(\4)?$

第一个适用于所有条件,第二个适用于除 part2 之外的所有条件(使用 GNU sed 4.1.5)

Does this work without alternation?

^((part)1(, \22)?)?(part2)?$

or why not this?

^((part)1(, (\22))?)?(\4)?$

The first works for all conditions the second for all but part2(using GNU sed 4.1.5)

时光是把杀猪刀 2024-12-21 03:32:20

或者你可以使用这个:

^(?:part[12]|(part)1,\12)$

Or you can use this:

^(?:part[12]|(part)1,\12)$
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文