简体   繁体   English

正则表达式 findall() python 返回空列表

[英]Regex findall() python returning empty list

I am trying to count the number of times a user entered regular expression shows up in any file, but the list created by findall keeps returning as empty.... help is appreciated!我正在尝试计算用户输入的正则表达式出现在任何文件中的次数,但由 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)

The error is in the line:错误在该行中:

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

You are not referencing the variable properly.您没有正确引用变量。 Do:做:

matches = re.findall(reg, line)

or similar.或类似的。 Doc .文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM