使用Python以正确的顺序查找一组模式的regex出现

2024-04-24 12:27:45 发布

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

我正在分析一系列的文本文件以获取一些模式,因为我想将它们提取到其他文件中。在

一种说法是,我想从文件中“删除”除了匹配项之外的所有内容。在

例如,如果我有pattern1、pattern2、pattern3作为匹配的pattern,我希望输入以下内容:

bla bla
pattern1
pattern2
bla bla bla
pattern1
pattern3
bla bla bla
pattern1

给出以下输出:

^{2}$

我可以使用re.findall并成功地获得任何模式的匹配列表,但是考虑到每个模式的匹配项在文件中是混合的,我想不出保持顺序的方法。在

谢谢你的阅读。在


Tags: 文件方法re内容列表顺序模式pattern
2条回答

这是一个“复制这个然后开始”格式的答案。在

import re

#lets you add more whenever you want
list_of_regex = [r"aaaa",r"bbbb",r"cccc"]

#hold the completed pattern
pattern_string = r"^("

#combines the patterns
for item in list_of_regex:
    pattern_string += "|".join(list_of_regex)

pattern_string += r")"

#open the file that you are reading
fr = open(FILE_TO_READ)

#holds the read files strings
search_string = fr.read()

#close the file
fr.close()

#open the file you want to write to
fw = open(FILE_TO_WRITE, 'w')

#write the results of findall into the file (as requested)
fw.writelines(re.findall(pattern_string,search_string))

#close the file
fw.close()

把它们组合成一个单一的模式。对于示例代码,请使用以下模式:

^pattern[0-9]+

如果事实上更复杂,那就试试吧

^{pr2}$

相关问题 更多 >