Search code examples
pythonpython-3.xregexparametersregex-group

How do I put a parameter to a function whose return is inside a re.sub()?


import re

def one_day_or_another_day_relative_to_a_date_func(m, type_of_date_unit_used):
    input_text = m.group()

    print(repr(input_text))

    if (type_of_date_unit_used == "year"): a = "YYYY-mm-dd"
    elif (type_of_date_unit_used == "month"): a = "yyyy-MM-dd"
    elif (type_of_date_unit_used == "day"): a = "yyyy-mm-DD"
    
    return a


def identify_one_day_or_another_day_relative_to_a_date(input_text, type_of_date_unit_used = "day"):
    date_capture_pattern = r"([123456789]\d*-[01]\d-[0-3]\d)(\D*?)"

    input_text = re.sub(date_capture_pattern, one_day_or_another_day_relative_to_a_date_func, input_text, re.IGNORECASE) #This is the line

    return input_text


input_text = "En 2012-06-12 empezo y termino en algun dia del 2023"
print(identify_one_day_or_another_day_relative_to_a_date(input_text, "month"))

I need to pass the parameter "month" when calling the one_day_or_another_day_relative_to_a_date_func function in the re.sub()

The output that I need with this parameter

"En yyyy-MM-dd empezo y termino en algun dia del 2023"

Solution

  • You can directly pass the parameters inside re.sub.

    import re
    
    
    def one_day_or_another_day_relative_to_a_date_func(m, type_of_date_unit_used):
        print(repr(m))
    
        if type_of_date_unit_used == "year":
            a = "YYYY-mm-dd"
        elif type_of_date_unit_used == "month":
            a = "yyyy-MM-dd"
        elif type_of_date_unit_used == "day":
            a = "yyyy-mm-DD"
    
        return a
    
    
    def identify_one_day_or_another_day_relative_to_a_date(input_text, type_of_date_unit_used="day"):
        date_capture_pattern = r"\d{4}\-\d{2}\-\d{2}"
        pattern_matched = ''.join(re.findall(date_capture_pattern, input_text))
        input_text = re.sub(date_capture_pattern,
                            one_day_or_another_day_relative_to_a_date_func(pattern_matched, type_of_date_unit_used),
                            input_text,
                            re.IGNORECASE)  # This is the line
    
        return input_text
    
    
    input_text = "En 2012-06-12 empezo y termino en algun dia del 2023"
    print(identify_one_day_or_another_day_relative_to_a_date(input_text, "month"))
    >>> '2012-06-12'
    >>> En yyyy-MM-dd empezo y termino en algun dia del 2023