正则表达式模式以任何顺序查找单词
regex pattern to find words in any order
我有以下字符串:
每个字符串都是用户通过命令行给出的答案,用于回答您想在分析中包括哪些地区的问题?
仅当字符串中存在 combine、online 或 store 并且它们由逗号和空格(或两者)分隔时,模式才有效。
下面是一些例子。
有效测试用例:
combine
combine, online, store
store online
online
无效的测试用例:
combine, anything else
anything else combine
combine-online
这是一个可以解决问题的正则表达式:
>>> import re
>>> cases = '''\
combine
combine, online, store
store online
online
combine, anything else
anything else combine
combine-online
'''.splitlines()
>>> for line in cases:
if re.match(r'^(combine|online|store)([ ,]+(combine|online|store))*$', line):
print(line)
这给出了这个输出:
combine
combine, online, store
store online
online
"allowed words" 的列表只包含 space 和逗号怎么样?
^(?:combine|online|store| |,)+$
我有以下字符串:
每个字符串都是用户通过命令行给出的答案,用于回答您想在分析中包括哪些地区的问题?
仅当字符串中存在 combine、online 或 store 并且它们由逗号和空格(或两者)分隔时,模式才有效。
下面是一些例子。
有效测试用例:
combine
combine, online, store
store online
online
无效的测试用例:
combine, anything else
anything else combine
combine-online
这是一个可以解决问题的正则表达式:
>>> import re
>>> cases = '''\
combine
combine, online, store
store online
online
combine, anything else
anything else combine
combine-online
'''.splitlines()
>>> for line in cases:
if re.match(r'^(combine|online|store)([ ,]+(combine|online|store))*$', line):
print(line)
这给出了这个输出:
combine
combine, online, store
store online
online
"allowed words" 的列表只包含 space 和逗号怎么样?
^(?:combine|online|store| |,)+$