簡體   English   中英

Python:匹配文件中的正則表達式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM