File Content Matcher with Regex

  • Share this:

Code introduction


This function takes two arguments, the first is the file path, and the second is a regular expression pattern. The function returns all strings that match the regular expression in the file.


Technology Stack : os, re

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re

def read_file(file_path, pattern):
    with open(file_path, 'r') as file:
        content = file.read()
        matches = re.findall(pattern, content)
        return matches

def xxx(arg1, arg2):
    if not os.path.isfile(arg1):
        return "File does not exist"
    pattern = arg2
    matches = read_file(arg1, pattern)
    return matches                
              
Tags: