Regex Python Searching dates

0
resultado_limpo = ((busca.find_all(string=re.compile(r'\d{2}\/\d{2}\/\d{4}\n\t\t\t\t\t\t\t\t'))))

I'm trying to fetch dates in dd / mm / yyyy format I need to search with only year 2016 and have how I put the month in the variable case inside my filter being that I'll get the month with datetime

    
asked by anonymous 19.09.2016 / 13:06

2 answers

1
mes = '07';
ano = '2016';

busca.find_all(string=re.compile("\d{2}\/%s\/%s\n\t\t\t\t\t\t\t\t" % (mes,ano), re.IGNORECASE));

You basically generate a string with replacements to be made and compile them after they occur.

    
19.09.2016 / 14:16
1
  

Note: Regular expression is not validating the date format, if   want the regex to validate the format: dd / mm / dddd

     

Regex

for dd / mm / yyyy

     

But if you just want to get it, it's okay

To capture elements within a regular expression, use groups.

Reference link

With them it is possible in the regular expression return to store the value in a language variable.

To define groups, use the format:

(?P<nome_variavel>regex)

So for your regex to pick up only the years 2016 and still capturing the month to be handled by the language first creates the regex.

"\d{2}\/\d{2}\/2016"

Then add the group you want to capture ..

"\d{2}\/(?P<mes>\d{2})\/2016"

Then use the language:

>>> import re
>>> padrao = re.compile("\d{2}\/(?P<mes>\d{2})\/2016")
>>> string_procurada = "Data de hoje: 25/09/2016"
>>> resultado = re.findall(padrao,string)
>>> resultado
['09']

Then just do the necessary treatments: cast to int, add to a list ..

    
25.09.2016 / 18:33