简体   繁体   中英

Python Regex search not showing month text

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM