hou*_*oft 52 python regex list
我有一个python中的正则表列表和一个字符串.有没有一种优雅的方法来检查列表中的至少一个正则表达式是否与字符串匹配?通过优雅,我的意思是比简单地循环遍历所有正则表达式并检查字符串并在找到匹配时停止更好.
基本上,我有这个代码:
list = ['something','another','thing','hello']
string = 'hi'
if string in list:
pass # do something
else:
pass # do something else
Run Code Online (Sandbox Code Playgroud)
现在我想在列表中有一些正则表达式,而不仅仅是字符串,我想知道是否有一个优雅的解决方案来检查匹配替换if string in list:.
提前致谢.
nos*_*klo 90
import re
regexes = [
# your regexes here
re.compile('hi'),
# re.compile(...),
# re.compile(...),
# re.compile(...),
]
mystring = 'hi'
if any(regex.match(mystring) for regex in regexes):
print 'Some regex matched!'
Run Code Online (Sandbox Code Playgroud)
Ned*_*der 85
import re
regexes = [
"foo.*",
"bar.*",
"qu*x"
]
# Make a regex that matches if any of our regexes match.
combined = "(" + ")|(".join(regexes) + ")"
if re.match(combined, mystring):
print "Some regex matched!"
Run Code Online (Sandbox Code Playgroud)
这是我根据其他答案所寻求的:
raw_list = ["some_regex","some_regex","some_regex","some_regex"]
reg_list = map(re.compile, raw_list)
mystring = "some_string"
if any(regex.match(mystring) for regex in reg_list):
print("matched")
Run Code Online (Sandbox Code Playgroud)
Ned和Nosklo的答案混合在一起。可以保证任何长度的作品...希望您喜欢
import re
raw_lst = ["foo.*",
"bar.*",
"(Spam.{0,3}){1,3}"]
reg_lst = []
for raw_regex in raw_lst:
reg_lst.append(re.compile(raw_regex))
mystring = "Spam, Spam, Spam!"
if any(compiled_reg.match(mystring) for compiled_reg in reg_lst):
print("something matched")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56384 次 |
| 最近记录: |