gpt4 book ai didi

Python 正则表达式匹配多行文本

转载 作者:行者123 更新时间:2023-11-28 22:19:43 25 4
gpt4 key购买 nike

我在文件中有一个文本。

INCLUDE '.\..\..\
FE_10-28\
ASSY.bdf'

INCLUDE '.\..\..\FE_10-28\standalone\COORD.bdf'

$ INCLUDE '.\..\..\FE_10-28\standalone\bracket.bdf'

$ INCLUDE '.\..\..\
$ FE_10-28\standalone\
$ ITFC.bdf'

我想要一个表达式来捕获字符串(应该跳过以 $ 开头的行):

['.\..\..\FE_10-28\ASSY.bdf', '.\..\..\FE_10-28\standalone\COORD.bdf']

我设法过滤了单行字符串:

    with open(bdf_name,'r') as f:
file_buff = f.readlines()

text = ''.join(file_buff)
regex_incl = re.compile("[^$]\s+include\s+\'(.*)\'",re.IGNORECASE|re.MULTILINE)
print(regex_incl.findall(text))

但是,多行会怎样呢?

最佳答案

你可以使用这个正则表达式:

>>> raw = '''
... INCLUDE '.\..\..\
FE_10-28\
ASSY.bdf'

INCLUDE '.\..\..\FE_10-28\standalone\COORD.bdf'

$ INCLUDE '.\..\..\FE_10-28\standalone\bracket.bdf'

$ INCLUDE '.\..\..\
$ FE_10-28\standalone\
$ ITFC.bdf'... ... ... ... ... ... ... ... ... ...
... '''
>>>
>>> re.findall(r"^INCLUDE\s+'(.+?)'\n", raw, re.M|re.DOTALL)
['.\\..\\..FE_10-28ASSY.bdf', '.\\..\\..\\FE_10-28\\standalone\\COORD.bdf']

关于Python 正则表达式匹配多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49505910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com