[英]python regex find matched string
我試圖在Python中使用正則表達式在字符串中找到匹配的字符串。 該string
如下所示:
band 1 # energy -53.15719532 # occ. 2.00000000
ion s p d tot
1 0.000 0.995 0.000 0.995
2 0.000 0.000 0.000 0.000
tot 0.000 0.996 0.000 0.996
band 2 # energy -53.15719532 # occ. 2.00000000
ion s p d tot
1 0.000 0.995 0.000 0.995
2 0.000 0.000 0.000 0.000
tot 0.000 0.996 0.000 0.996
band 3 # energy -53.15719532 # occ. 2.00000000
我的目標是在tot
之后找到字符串。 因此,匹配的字符串將類似於:
['0.000 0.996 0.000 0.996',
'0.000 0.996 0.000 0.996']
這是我當前的代碼:
pattern = re.compile(r'tot\s+(.*?)\n', re.DOTALL)
pattern.findall(string)
但是,輸出給了我:
['1 0.000 0.995 0.000 0.995',
'0.000 0.996 0.000 0.996',
'1 0.000 0.995 0.000 0.995',
'0.000 0.996 0.000 0.996']
任何我做錯事的想法嗎?
您不需要DOTALL
標志。 刪除它並改用MULTILINE
。
pattern = re.compile(r'^\s*tot(.*)', re.MULTILINE)
這匹配以tot
開頭的所有行。 該行的其余部分將在第1組中。
引用文檔 ,重點是:
re.DOTALL
標記為
'.'
特殊字符完全可以匹配任何字符, 包括換行符 ; 沒有此標志,'.'
將匹配換行符以外的任何內容。
請注意,無需正則表達式,您可以輕松地做到這一點。
with open("input.txt", "r") as data_file:
for line in data_file:
items = filter(None, line.split(" "))
if items[0] == "tot":
# etc
您正在使用re.DOTALL,這意味着點“。” 會匹配所有內容,甚至是換行符,從本質上來說,它會找到“ tot” -s以及下一個換行符之前的所有內容:
tot
1 0.000 0.995 0.000 0.995
和
tot 0.000 0.996 0.000 0.996
刪除re.DOTALL應該可以解決您的問題。
編輯:實際上,DOTALL標志不是真正的問題(盡管不必要)。 模式中的問題是\\ s +與換行符匹配。 用單個空格代替可以解決此問題:
pattern = re.compile(r'tot (.*?)\n')
使用re.findall
函數和特定正則表達式模式的替代解決方案:
# str is your inital string
result = re.findall('tot [0-9 .]+(?=\n|$)', str)
print(result)
輸出:
['tot 0.000 0.996 0.000 0.996', 'tot 0.000 0.996 0.000 0.996']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.