我正在尝试编写一个简单的脚本,它将从一堆Python源代码文件中删除一个预先存在的头块(除其他外)。例如:
##########################################
## This is a header block that
## I want to erase.
## It occurs at the top of a file,
## has a variable number of lines,
## and maybe some blank ones thrown in, like
##
########################################
this is some code that needs to be preserved
# and a comment I don't want touched
followed by some more code...我的当前方法是使用一个正则表达式,该表达式将捕获整个块并使用空字符串对其进行sub,如下所示:
regex = re.compile("^#.*$\n", re.MULTILINE)
regex.sub('', filetext, count=1)我在这个re字符串上尝试了100个变体,包括:
"^#.*"
"^#+.*"
"^#.*\n"
...但是,所有这些都只删除了块的第一行(#‘s在顶部)。
the pattern character '^' matches at the beginning of the string and at the
beginning of each line (immediately following each newline);对我来说,这意味着它将在一次匹配中包含与给定模式匹配的所有连续行。显然,我对re.MULTILINE的理解是错误的,或者我写错了regexp。有人能帮我了解一下发生了什么并完成我想要做的事吗?谢谢。
发布于 2014-02-20 00:28:13
您将regex替换限制在以下一行中的仅1个替换最大值:
regex.sub('', filetext, count=1)摆脱count=1
regex.sub('', filetext)count参数限制了文档中的最大替换数:
可选参数计数是要替换的模式出现次数的最大值;计数必须是非负整数。如果省略或为零,则将替换所有出现的事件。
https://stackoverflow.com/questions/21895526
复制相似问题