首页 > 解决方案 > 在这种情况下我应该使用什么正则表达式?

问题描述

我想创建一个正则表达式以仅获取以日期开头的行(忽略其他行)以及上面带有“前缀”一词的行。正则表达式应该如何?

我的 txt 文件中有以下结构:

                                                        Prefix : 0051601

    Data     Material                                       No. OS  Hist. Nr/Controle        Quant.       Vlr.Unit.            Vlr.Total 
 ----------------------------------------------------------------------------------------------------------------------------------------
 13/01/2008  00101050 Lampada farol H5 24V                          003   4863                2,000        9,870556              19,7411 
                                                                                        ====== Total dia 13/01/2008 ======
                                                                     Entradas :                                                         
                                                                     Saídas   :               2,000                              19,7411
                                                                     -------------------------------------------------------------------

主要代码是:

import glob, os
import re

os.chdir("./txtfiles/")

for file in glob.glob("*.txt"):

    with open(file) as f:
        content = f.readlines()
        # not working, just for test purpose
        result = re.match(r'Prefix', content, re.M|re.I)
        if result:
            print(content)
        else:
            print "no match found!"

标签: pythonregex

解决方案


您可以使用此正则表达式来识别这些行。
使用 findall 获取所有行。

r"(?im)(?:^[^\S\r\n]*\d+/\d+/\d+|.*\bprefix).*"

https://regex101.com/r/rAl3r6/1


推荐阅读