Python: Searching for date using regular expression

Question:

I am searching for date information, in the format of 01-JAN-2023 in a extracted text, and the following regular expression didn’t work. Can b and Y be used this way?

import re

rext = 'This is the testing text with 01-Jan-2023'

match = re.search(r"dbY", rext)
print(match)
Asked By: TTZ

||

Answers:

You can use this regular expression:

match = re.search(r"d{2}-[a-zA-Z]{3}-d{4}", rext)
print(match.group())

d matches a digit (equivalent to [0-9]).

[a-zA-Z] matches an upper- or lower-case letter.

{n} matches the preceding pattern n times.

Answered By: Unmitigated
import re

rext = 'This is the testing text with 01-Jan-2023'

match = re.search(r"d+-w+-d+", rext)
print(match)
<re.Match object; span=(30, 41), match='01-Jan-2023'>
Answered By: Laurent B.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.