[英]Python re: if string has one word AND any one of a list of words?
I want to find if a string matches on this rule using a regular expression: 我想使用正则表达式查找字符串是否与此规则匹配:
list_of_words = ['a', 'boo', 'blah']
if 'foo' in temp_string and any(word in temp_string for word in list_of_words)
The reason I want it in a regular expression is that I have hundreds of rules like it and different from it so I want to save them all as patterns in a dict. 我想要它在正则表达式中的原因是我有数百个类似于它的规则,因此我希望将它们全部保存为dict中的模式。
The only one I could think of is this but it doesn't seem pretty: 我唯一能想到的就是这个,但它看起来并不漂亮:
re.search(r'foo.*(a|boo|blah)|(a|boo|blah).*foo')
You can join the array elements using |
您可以使用|
来连接数组元素 to construct a lookahead assertion regex: 构造一个先行断言正则表达式:
>>> list_of_words = ['a', 'boo', 'blah']
>>> reg = re.compile( r'^(?=.*\b(?:' + "|".join(list_of_words) + r')\b).*foo' )
>>> print reg.pattern
^(?=.*\b(?:a|boo|blah)\b).*foo
>>> reg.findall(r'abcd foo blah')
['abcd foo']
As you can see we have constructed a regex ^(?=.*\\b(?:a|boo|blah)\\b).*foo
which asserts presence of one word from list_of_words
and matches foo
anywhere. 正如你所看到的,我们构造了一个正则表达式^(?=.*\\b(?:a|boo|blah)\\b).*foo
,它从list_of_words
断言存在一个单词,并在任何地方匹配foo
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.