2012-12-20 31 views
-1

我有一個列表,我想找出列表中的任何一個項目是否使用正則表達式在字符串中。有沒有辦法做到這一點?如何使用正則表達式找出Python列表中的任何一項是否在字符串中?

+0

請注意,您沒有接受任何其他問題的答案 - 這可能會使人們回答這個問題。 –

+0

@Lattyware:'t已經過了漫長的一天,也許我需要擺脫..:P –

+0

@MartijnPieters - 我想起來同樣的事情。 – mgilson

回答

5

當然。

myregex = re.compile(...) 
print any(myregex.search(s) for s in my_list_of_strings) 

或可能:

regexs = [re.compile(s) for s in my_list_of_regex_strings] 
any(r.search(my_string) for r in regexs) 

,我想可能是同樣的事情:

regex_str = '|'.join('(?:%s)'%re.escape(s) for s in list_of_regex_strings) 
re.search(regex_str,my_string) 

我現在還不能告訴你試圖去與該走哪條路...

最後,如果你真的想知道哪個正則表達式匹配:

next(regex_str for regex_str in regex_str_list if re.search(regex_str,mystring)) 

這會引發StopIteration異常(您可以捕獲),如果沒有正則表達式的匹配。

+0

我認爲他想要做相反的事情,如果這樣,他從一列搜索目標開始,然後找到所有這些發生在給定字符串中。 –

+0

@ sr2222 - 我已經重新閱讀了大約6或7次的問題,但我仍然不確定... – mgilson

+0

「查找[a]列表中的任何一項是否在字符串中」引導我思考他有一套目標,並希望看看它們中的任何一個是否出現在字符串中。所以基本上'匹配'模式中的一堆or'ed值。或者甚至只是'任何(如果x在字符串中,x代表目標)'。 –

-2
for each item in list: 
    use regex on string 

這就是儘可能具體給你的問題的普遍性質。

編輯:這是僞代碼,而不是Python

0

我假設OP是詢問如何找出如果在字符串列表中的任何一個項目使用正則表達式的模式相匹配。

# 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)) 
相關問題