[英]Python:Matching Regular Expression in file
我用Python編寫了以下代碼以匹配文件中的字符串:
#!/usr/bin/python
import re
f = open('file','r')
for line in f:
mat = re.search(r'This',line)
mat.group(0)
f.close()
我使用以下文件作為輸入:
This is the first line
That was the first line
但是當我嘗試搜索表達式This
它會導致None
輸出。 為什么字符串不匹配?
您應該使用with
語法來確保文件正確打開。
您沒有先檢查是否有匹配項,因此在檢查第二行時會崩潰。 這是一些工作代碼:
import re
with open('file','r') as f:
for line in f:
mat = re.search(r'This',line)
if mat:
print mat.group(0)
我更喜歡事先編譯模式,並在每次迭代中使用它。
import re
pat = re.compile(r'This')
with open('file') as f:
for line in f:
mat = pat.search(line)
if mat:
print(mat.group(0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.