-2

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!


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)
  • Does this answer your question? [Is there a Python equivalent to Ruby's string interpolation?](/q/4450592/90527) – outis Sep 01 '22 at 10:14

1 Answers1

1

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.

M B
  • 2,700
  • 2
  • 15
  • 20