首页 > 解决方案 > Python 脚本中的多个正则表达式搜索。

问题描述

我对这一切都很陌生。

我想在一个 Python 脚本中批量处理几个正则表达式。

当正则表达式在 Notepad++ 中搜索文本文件时,每个正则表达式都可以正常工作。

但是,当组合时它不起作用。不工作意味着我的 Python 脚本不返回使用 Notepad++ 搜索找到的有效命中。

运行 Python 3.7。

提前致谢。

# import Python's regular expression module
import re

# file to check; assumes target file is in the same dir as Python script
target = 'test target file.txt'  

# declare series of regexes; see top for explanation of each
regexes = [re.compile('^\+'),
       re.compile('^[\s+][A-Z]'),
       re.compile('\d$\r\n[cm,%,\),l,ml,hPa,°,bar,psi,V,W,]'),
       re.compile('^[1-9]{1,2}\.(.*)\r\n^\r\n^[1-9]{1,2}\.(.*)'),
       re.compile('FN-'),
       re.compile('gfx'),
       re.compile('tbl'),
       re.compile('Missing link'),
       ]

# open target file, search for matches, output to screen
with open(target) as fp:  
   for line in target:
    for cnt, line in enumerate(fp):
      if any(regex.match(line) for regex in regexes):
        print("Line {}: {}".format(cnt, line))

标签: pythonregex

解决方案


推荐阅读