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)
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.
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'>
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)
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.
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'>