Regex Python Searching dates

Asked

Viewed 699 times

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 am trying to find dates in dd/mm/yyyy format need search with year only 2016 and have how I put the month in the variable case inside my filter and I’ll get the month with datetime

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));

Basically you generate a string with replacements to be made and compile after they occur.

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 take it

To capture elements within a regular expression groups are used.

Reference link

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

To define groups use the format:

(?P<nome_variavel>regex)

So for its regex to take only the years 2016 and still capturing the month to be treated 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 it in 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']

Ai then only do the necessary treatments : cast to int, add to a list..

  • Very good !!!!!

  • Mark the answer that helped you :D.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.