-1

リストがあり、そのリスト内のいずれかの項目が正規表現を使用して文字列に含まれているかどうかを調べたいと思います。これを行う方法はありますか?

4

3 に答える 3

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により、一致する正規表現がない場合に (キャッチできる) 例外が発生します。

于 2012-12-20T21:30:17.123 に答える
0

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))
于 2012-12-20T21:43:33.977 に答える
-2
for each item in list:
   use regex on string

あなたの質問の一般的な性質を考えると、それは可能な限り具体的です。

編集: これは疑似コードであり、python ではありません

于 2012-12-20T21:30:31.527 に答える