RegEx,在一行中找到匹配项并打印i

2024-05-16 22:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

从如下结构的文件中:

..............................
Delimiter [1]
..............................
blablabla
..............................
Delimiter CEO [2]
..............................
blabla
..............................
Delimiter [3]
..............................

[...]

..............................
Delimiter CEO [n-1]
..............................
blablabla
..............................
Delimiter [n]
..............................   

我编写了一个代码,它提取了所有的分隔符,但也提取了一些我不需要的行。我不需要的那些行导致my code不能正常运行。 我想在一个新的.txt文件中保存一行,如果那行有正则表达式“[a number]”。因此,为了更准确地提取,我用python编写了以下代码(如下this answer),使用re:

^{pr2}$

但是,在普罗瓦.txt'文件我只能找到正则表达式,所以我有一个文件与[1],[2]。。。[n-1],[n]。在


Tags: 文件代码answerretxtnumbermycode
1条回答
网友
1楼 · 发布于 2024-05-16 22:32:20

您的new_file是文件中找到的匹配项的列表(用match.group()+换行符填充)。在

您可以检查一行中是否存在\[\d+]匹配,并将该行输出到新文件中:

import re

reg = re.compile(r'\[\d+]') # Matches a [ char, followed with 1+ digits and then ]

with open('prova.txt', 'w') as f:     # open file for writing
    with open('testoestratto.txt','r',encoding='UTF-8') as myFile: # open file for reading
        for line in myFile:           # read myFile line by line
            if reg.search(line):      # if there is a match anywhere in a line
                f.write(line)         # write the line into the new file

相关问题 更多 >