[英]Python regex library can't match even though it should
我的劇本:
#!/usr/bin/env python
import os
import re
def grep(filepath, regex):
regObj = re.compile(regex)
res = []
with open(filepath) as f:
for line in f:
if regObj.match(line):
res.append(line)
return res
print(grep('/opt/conf/streaming.cfg', 'Port='))
假定遍歷給定文件中的各行並匹配提供的regex(如果存在),追加到res
並最終返回res
。
/opt/conf/streaming.cfg
的內容包含一行:
SocketAcceptPort=8003
仍然打印[]
怎么會?
檢查文檔是否存在re.match
,這是我們的第一句話:
如果在字符串開頭匹配零個或多個字符
注意“字符串開始”部分嗎? 您需要使用其他功能來匹配行中的任何地方。 例如,以下文檔中的match
為:
如果要在字符串中的任意位置找到匹配項,請使用search()代替
如果要查找端口列表,則可以不使用字符串比較:
#!/usr/bin/env python
import os
import re
def grep(filepath, substring):
res = []
with open(filepath) as f:
for line in f:
if substring in line:
res.append(line.rsplit("\n")[0])
return res
print(grep('/opt/conf/streaming.cfg', 'Port='))
給出結果:
['SocketAcceptPort=8003']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.