所以我在 python 中获得了一些输入,我需要使用正则表达式进行解析。
目前我正在使用这样的东西:
matchOK = re.compile(r'^OK\s+(\w+)\s+(\w+)$')
matchFailed = re.compile(r'^FAILED\s(\w+)$')
#.... a bunch more regexps
for l in big_input:
match = matchOK.search(l)
if match:
#do something with match
continue
match = matchFailed.search(l)
if match:
#do something with match
continue
#.... a bunch more of these
# Then some error handling if nothing matches
现在我通常喜欢 python,因为它简洁明了。但这感觉很冗长。我希望能够做这样的事情:
for l in big_input:
if match = matchOK.search(l):
#do something with match
elif match = matchFailed.search(l):
#do something with match
#.... a bunch more of these
else
# error handling
我是不是遗漏了什么,或者第一个表格是否和我要得到的一样整洁?
最佳答案
class helper:
def __call__(self, match):
self.match= match
return bool(match)
h= helper()
for l in big_input:
if h(matchOK.search(l)):
# do something with h.match
elif h(matchFailed.search(l)):
# do something with h.match
... # a bunch more of these
else:
# error handling
或者匹配器作为类方法:
class matcher:
def __init__(self):
# compile matchers
self.ok= ...
self.failed= ...
self....= ...
def matchOK(self, l):
self.match= self.ok(l)
return bool(self.match)
def matchFailed(self, l):
self.match= self.failed(l)
return bool(self.match)
def match...(self, l):
...
m= matcher()
for l in big_input:
if m.matchOK(l):
# do something with m.match
elif m.matchFailed(l):
# do something with m.match
... # a bunch more of these
else:
# error handling
关于python - 我怎样才能在 python 中整齐地处理几个正则表达式案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5510879/