python - 我怎样才能在 python 中整齐地处理几个正则表达式案例

标签 python

所以我在 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/

相关文章:

python - OpenCV "The function is not implemented. Rebuild the library with Windows"

python - Beautifulsoup、Python 和 HTML 自动页面截断?

python - 如果值相等,则将连续的子列表分组在一起,然后提取具有属性 = 'R' 的值

python - 如何将wav音频文件格式(样本宽度)转换为8位格式?

python - 即使 CLI session 关闭,也要继续在 AWS EC2 上运行 python 脚本

python - 使用标准库 Decimal 将运算符应用于非常长的十进制数时抑制科学记数法

python - 无法将所有文件移动到新文件夹

python - Tornado Facebook 获取请求。如何移至下一页

python - 使用字符串的特定部分。 python中某些条件之前和之后的部分

python - 如何知道我在 Python 中加载的库的位置?