Home > Blockchain >  How to conditionally perform regex replacement to get this output using re.sub()?
How to conditionally perform regex replacement to get this output using re.sub()?

Time:12-31

import re, datetime

input_text_substring = "del año, desde el año, o en el año desde donde ocurrio al de donde los años"

input_text_substring = re.sub(r"(?:del|de[\s|]*los|de[\s|]*el|el|los)[\s|]*(?:años|anos|año|ano)", 
                            str( int(datetime.datetime.today().strftime('%Y') )   1), 
                            input_text_substring)

print(repr(input_text_substring))

What regex should place here in (?:del|de[\s|]*los|de[\s|]*el|el|los) so that the correct replacements are given, since as you can see it should not always be applied in the same way

The wrong output that I get

'2023, des2023, o en 2023 desde donde ocurrio al de don2023'

And the output that I need

'2023, desde 2023, o en 2023 desde donde ocurrio al de donde 2023'

CodePudding user response:

You can use Positive lookbehind to capture the words after the space.

import datetime
import re

input_text_substring = "del año, desde el año, o en el año desde donde ocurrio al de donde los años"

input_text_substring = re.sub(r"(?:(?<=\s)|^)(?:del|el|los)\s(?:año[s]?|ano[s]?)",
                              str(int(datetime.datetime.today().strftime('%Y'))   1),
                              input_text_substring)

print(repr(input_text_substring))

>>> '2023, desde 2023, o en 2023 desde donde ocurrio al de donde 2023'
  • Related