我想寫一個簡單的腳本,將從一堆的Python源代碼文件(除其他事項)之外擦除預先存在的頭塊。例如:蟒蛇re.MULTILINE混淆
##########################################
## 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
字符串,包括:
"^#.*"
"^#+.*"
"^#.*\n"
...
但所有僅擦除塊的第一線(「#」 s的頂部的線)。 Python的聯機文檔說
the pattern character '^' matches at the beginning of the string and at the
beginning of each line (immediately following each newline);
這對我來說意味着它將在單個匹配中包含匹配給定模式的所有連續行。顯然,無論我對re.MULTILINE的理解是錯誤的,還是錯誤地寫了我的regexp。有人能幫助我瞭解發生了什麼,並完成我想要做的事情嗎?謝謝。
太棒了,這個工程。謝謝。你能解釋爲什麼我對多線模式的理解是錯誤的嗎?另外,爲什麼不是用這個字符串編譯的代碼中的所有其他註釋都不能編譯正則表達式? – wayeast