我有一个文件,其中包含我需要解析的以下格式化文件
field_1 {
field_2 {
....
}
field_i_want_to_replace {
....
}
....
}
....
我需要python中的预处理器来解析这些文件并删除某些特定字段的内容。在上面的示例中,处理过的文件如下所示:
field_1 {
field_2 {
....
}
field_i_want_to_replace {}
....
}
....
因此预处理器需要找到特定字段" field_i_want_to_replace"然后删除括号之间的内容。我尝试执行以下操作,但正则表达式无法正确解析文件。
regex = r'(field_i_want_to_replace )\{.*?\}'
print re.sub(regex,'field_i_want_to_replace {}', file_in_string)
我正在使用的正则表达式是否存在错误?
答案 0 :(得分:2)
您的.
字符与任何换行符都不匹配,因此在左侧括号后不会继续。
要更改此行为,只需将re.DOTALL
flag(或re.S
)作为关键字arg添加到re.sub
:
>>> regex = r'(field_i_want_to_replace )\{.*?\}'
>>> print re.sub(regex,'field_i_want_to_replace {}', file_in_string, flags=re.DOTALL)
field_1 {
field_2 {
....
}
field_i_want_to_replace {}
....
}