[英]python regular expression not matching file contents with re.match and re.MULTILINE flag
我正在讀取文件並將其內容存儲為多行字符串。 然后我遍歷我從 django 查詢中獲得的一些值,以根據查詢結果值運行正則表達式。 我的正則表達式似乎應該可以工作,並且如果我復制查詢返回的值就可以工作,但是由於某些原因,當所有部分都以這樣結束的方式一起工作時不匹配
我的代碼是:
with open("/path_to_my_file") as myfile:
data=myfile.read()
#read saved settings then write/overwrite them into the config
items = MyModel.objects.filter(some_id="s100009")
for item in items:
regexString = "^\s*"+item.feature_key+":"
print regexString #to verify its what I want it to be, ie debug
pq = re.compile(regexString, re.M)
if pq.match(data):
#do stuff
所以基本上我的問題是正則表達式不匹配。 當我將文件內容復制到一個大的舊字符串中,並復制由print regexString
行print regexString
,它確實匹配,所以我想有一些深奧的 python/django 事情正在發生(或者可能不是那么深奧因為 python 不是我的第一語言)。
例如, print regexString
的輸出是:
^\\s*productDetailOn:
文件內容:
productDetailOn:true,
allOff:false,
trendingWidgetOn:true,
trendingWallOn:true,
searchResultOn:false,
bannersOn:true,
homeWidgetOn:true,
}
運行 Python 2.7。 另外,轉儲了 item.feature 和 data 的類型,並且都是 unicode。 不確定這是否重要? 無論如何,在工作了幾個小時后,我的頭開始從辦公桌上掉下來,因此感謝您的幫助。 干杯!
根據文檔, re.match
永遠不允許在一行的開頭搜索:
請注意,即使在
MULTILINE
模式下,re.match()
也只會匹配字符串的開頭,而不是每行的開頭。
您需要使用re.search
:
regexString = r"^\s*"+item.feature_key+":"
pq = re.compile(regexString, re.M)
if pq.search(data):
關於原始字符串( r"^\\s+"
)的一個小說明:在這種情況下,它等效於"\\s+"
因為沒有\\s
轉義序列(如\\r
或\\n
),因此,Python 將其處理作為原始字符串文字。 盡管如此,始終使用 Python 中的原始字符串文字(以及其他語言中的相應符號)聲明正則表達式模式更安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.