[英]How can I find out if any one item in a Python list is in a string using regex?
I have a list and I'd like to find out if any one item in that list is in a string using regex. 我有一个列表,我想使用正则表达式找出该列表中是否有任何一项包含在字符串中。 Is there a way to do this? 有没有办法做到这一点?
Sure. 当然。
myregex = re.compile(...)
print any(myregex.search(s) for s in my_list_of_strings)
or maybe: 或者可能:
regexs = [re.compile(s) for s in my_list_of_regex_strings]
any(r.search(my_string) for r in regexs)
which I suppose is probably the same thing as : 我想可能与:
regex_str = '|'.join('(?:%s)'%re.escape(s) for s in list_of_regex_strings)
re.search(regex_str,my_string)
I still can't tell which way you're trying to go with this... 我仍然无法确定您要采用哪种方式...
Finally, if you actually want to know which regex matched: 最后,如果您实际上想知道哪个正则表达式匹配:
next(regex_str for regex_str in regex_str_list if re.search(regex_str,mystring))
This will raise a StopIteration
exception (that you can catch) if none of the regex's match. 如果没有一个正则表达式匹配项,将引发StopIteration
异常(您可以捕获)。
I'm assuming that OP is asking how to to find out if any one item in a list of strings matches a pattern using regex . 我假设OP正在询问如何使用regex查找字符串列表中的任何一项是否与模式匹配 。
# import the regex module
import re
# some sample lists of strings
list1 = ['Now', 'is', 'the', 'time', 'for', 'all', 'good', 'men']
list2 = ['Me', 'Myself', 'I']
# a regex pattern to match against (looks for words with internal vowels)
pattern = '.+[aeiou].+'
# use any() around a list comprehension to determine
# if any match via the re.match() function
any(re.match(pattern, each) for each in list1)
# if you're curious to determine just what is matching your expression, use filter()
list(filter(lambda each: re.match(pattern, each) , list2))
for each item in list:
use regex on string
thats as specific as possible given the generalistic nature of your question. 鉴于您的问题的一般性,多数意见应尽可能具体。
EDIT: this is psuedocode, not python 编辑:这是psuedocode,而不是python
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.