string to regex filter code example
Example: Filter regex
import os
import re
def find_files(file_type):
os.chdir(path)
with os.scandir(path) as it:
for entry in it:
if entry.name.endswith(file_type) and entry.is_file():
yield entry.name
def find_in_file(files, pattern):
for file in files:
with open(file, encoding='utf-8') as f:
for index, line in enumerate(f, 1):
for match in re.finditer(pattern, line):
print(f'Found <{line.strip()}> in file <{file}> on line <{index}>')
if __name__ == '__main__':
path = r'E:\div_code\new\cat_pic'
pattern = re.compile(r'cat|dog\d\d(?!\d)')
file_type = '.txt'
files = find_files(file_type)
find_in_file(files, pattern)