Reputation: 817
I'm trying to validate the String against RegEx pattern and then I want month and Year from pattern search. The pattern match is good, I can see date and year but month is empty
import re
txt = '25-Nov-18'
pattern = re.compile('^(\d{1,2})(\/|-)[a-zA-Z]{3}(\/|-)(\d{2})$')
if pattern.match(txt):
m = pattern.search(txt)
print(m.group(1), m.group(2), m.group(3), m.group(4))
Result is
25 - - 18
FYI: m.group(0) is 25-Nov-18
Am I missing anything here? Is there any better way than this?
Upvotes: 0
Views: 36
Reputation: 3232
You're just missing some parenthesis and another group, you have to surround in parenthesis everything you want to recover.
import re
txt = '25-Nov-18'
pattern = re.compile('^(\d{1,2})(\/|-)([a-zA-Z]{3})(\/|-)(\d{2})$')
if pattern.match(txt):
m = pattern.search(txt)
print(m.group(1), m.group(2), m.group(3), m.group(4), m.group(5))
Upvotes: 1