正则表达式匹配的长字符串与\read from fi断开

2024-10-02 00:44:27 发布

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

在我读到的文件中,我有几行:

你知道吗文件内容.py你知道吗

header.Description      ="long"\
"description"
header.Priority         =1
header.Type             ="short"

我需要正则表达式,它将与断开的行和未断开的行相匹配。现在我这样做:

with open('fileContent.py') as f:
    fileContent = f.read()
template = r'\nheader\.%s\s*=\s*.+(\\n.+)?'
values = ['Description', 'Priority']
for value in values:
    print re.search(re.compile(template % str(value)), fileContent).group(0)

我收到:

header.Priority         ="1"

header.Description      ="long"\

如果我将template更改为不使用原始字符串:

template = '\nheader\\.%s\\s*=\\s*.+(\\\n.+)?'

我收到:

header.Priority         ="1"
header.Type             ="short"

header.Description      ="long"\
"description"

我如何构建正则表达式来匹配上面的两行断线字符串,并且只匹配一行字符串?我不想让一行包含header.Type,因为我不想找它! 为什么'\\\n'不能像我预期的那样工作-匹配反斜杠+换行符序列。你知道吗


Tags: 文件字符串pyvaluetypetemplatedescriptionlong
2条回答

您的模式不匹配backslash+newline的原因是您有r'\\n',这意味着a backslash + 'n'。你知道吗

对于上述情况,可以尝试以下正则表达式:

\nheader\.Description\s*=\s*[^\r\n]+(?P<broken_line>\\\n.+)

demo here。你知道吗

但是不建议用正则表达式解析代码,因为Python代码不是正则语言。使用^{}。你知道吗

试试这个正则表达式:

(?:[^\r\n]+\\[\r\n]*)+|[^\r\n]+

See the DEMO

相关问题 更多 >

    热门问题