正则表达式中的AND/OR运算符如何表示? [英] How is the AND/OR operator represented as in Regular Expressions?

查看:649
本文介绍了正则表达式中的AND/OR运算符如何表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编程一种词汇算法,该算法可以检查用户是否正确输入了单词.我有以下情况: 该词的正确解决方案是"part1,part2". 用户应该能够输入"part1"(答案1),"part2"(答案2)或"part1,part2"(答案3). 现在,我尝试将用户提供的字符串与以下自动创建的正则表达式进行匹配:

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)$

这只会返回正确的答案1和2,而答案3将会是错误的.我现在想知道是否存在类似于|的运算符.表示and/or而不是either...or.

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?

推荐答案

我将假定您要动态构建一个正则表达式,以包含除part1和part2之外的其他单词,并且您希望顺序无关紧要.如果是这样,您可以使用以下方式:

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))+$

正匹配项:

part1
part2, part1
part1, part2, part3

否定匹配:

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

这篇关于正则表达式中的AND/OR运算符如何表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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