Home > other >  How to return a date from a text using regex?
How to return a date from a text using regex?

Time:10-25

I have next code:

import re

text = "Hi! Today is  24/10/2021 and we will have an importan event"

def searchForDate(text):
    getDate = re.match('(^(((0[1-9]|1[0-9]|2[0-8])[\/](0[1-9]|1[012]))|((29|30|31)[\/](0[13578]|1[02]))|((29|30)[\/](0[4,6,9]|11)))[\/](19|[2-9][0-9])\d\d$)|(^29[\/]02[\/](19|[2-9][0-9])(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96)$)', text)
    if getDate:
        return getDate
    else:
        return 'Text doesn´t contain any date'

print(searchForDate(text))

And what I want is to return date from a text using regex with dd/mm/yyyy format, for example get in console:

'24/10/2021'

But instead of that I just get:

'Text doesn´t contain any date'

I have tried with other regular expression with dd/mm/yyyy format, but my code stills showing in console Text doesn´t contain any date. I hope you can help me, thanks!

CodePudding user response:

May be this will help

import re

text = "Hi! Today is  24/10/2021 and we will have an important event"

data = re.findall("../../....", text)

print(data)

OP

['24/10/2021']

CodePudding user response:

The anchors are causing the match to fail. If you want a date embedded in another string you can use something like

(((0[1-9]|1[0-9]|2[0-8])[\/](0[1-9]|1[012]))|((29|30|31)[\/](0[13578]|1[02]))|((29|30)[\/](0[4,6,9]|11)))[\/](19|[2-9][0-9])\d\d|29[\/]02[\/](19|[2-9][0-9])(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96) as your regex (note the removed anchors from both expressions).

CodePudding user response:

Your regex matches on the full string, for two reasons. You used anchors to the star (^) and end ($) of line, and re.match matches only at the beginning. You should remove your anchors and use re.search

CodePudding user response:

You can use '\d' for matching any digit and set the count of it by '{}'. Then, if match is true, you must use .group() to extract the date:

import re


def searchForDate(text):
    date = re.search(r"\d{2}/\d{2}/\d{4}", text)

    if date:
        return date.group()
    else:
        return 'Text doesn´t contain any date'


text = "Hi! Today is  24/10/2021 and we will have an importan event"

print(searchForDate(text))
  • Related