在我读到的文件中,我有几行:
你知道吗文件内容.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'
不能像我预期的那样工作-匹配反斜杠+换行符序列。你知道吗
您的模式不匹配
backslash+newline
的原因是您有r'\\n'
,这意味着a backslash + 'n'
。你知道吗对于上述情况,可以尝试以下正则表达式:
见demo here。你知道吗
但是不建议用正则表达式解析代码,因为Python代码不是正则语言。使用^{} 。你知道吗
试试这个正则表达式:
See the DEMO
相关问题 更多 >
编程相关推荐