簡體   English   中英

正則表達式 findall() python 返回空列表

[英]Regex findall() python returning empty list

我正在嘗試計算用戶輸入的正則表達式出現在任何文件中的次數,但由 findall 創建的列表一直返回為空......感謝幫助!


reg = input('Enter a regular expression ')

fname = input('Enter file name ')

try:
    fhand = open(fname, 'r')
except:
    print('Cannot open file')
    quit()

for line in fhand:
    line = line.strip()
    matches = re.findall('(reg)', line)
print(matches, len(matches))
print(fname, 'had', len(matches), 'that matched', reg)

錯誤在該行中:

matches = re.findall('(reg)', line)

您沒有正確引用變量。 做:

matches = re.findall(reg, line)

或類似的。 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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