简体   繁体   English

Python re:如果字符串有一个单词和任何一个单词列表?

[英]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.

相关问题 从列表中的一个字符串中搜索任何单词或单词组合(python) - Search for any word or combination of words from one string in a list (python) 使用正则表达式查找字符串中除单词中的所有单词以外的所有单词 - Find all the words in string except one word in python with regex Python:大写字符串中除一个单词以外的单词的第一个字符 - Python : Capitalize first character of words in a string except one word 将一个列表中的单词与其他列表中的单词进行比较 - Comparing a word in one list with words in other lists 如何使用 python 在一个单词中保存 5 个单词 - how to save 5 words in one word using python Python重新捕获每个单词的一个匹配项 - Python re capture one match per word 仅当另一个单词中第一个单词的索引都匹配时,如何返回一个单词与列表中所有其他单词的索引的匹配? - How match index of one word to index of all other words in list return only if all index match of first word in other any word? Python Regex:匹配由一个其他单词完全分隔的任何重复单词 - Python Regex: match any repeated words that are separated by exactly one other word 如何索引 Python 中每行超过一个单词的输入单词 - How to index input words that has more than one word per line in Python 如何让python在列表中搜索一个单词而不是列表中所有单词的文本? - How do I get python to search text for one word in a list rather than all the words in a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM