Search code examples
regexpython-3.xregex-lookaroundsregex-groupregex-greedy

RegEx for matching the month, day and year


I'm trying to find a regular expression to extract the month, day and year from a datetime stamp in this format:

01/20/2019 12:34:54

It should return a list:

['01', '20', '2019']

I know this can be solved using:

dt.split(' ')[0].split('/')

But, I'm trying to find a regex to do it:

[^\/\s]+ 

But, I need it to exclude everything after the space.


Solution

  • As you are expecting the date month and year to be returned as a list, you can use this Python code,

    import re
    
    s = '01/20/2019 12:34:54'
    print(re.findall(r'\d+(?=[ /])', s))
    

    Prints,

    ['01', '20', '2019']
    

    Otherwise, you can better write your regex as,

    (\d{2})/(\d{2})/(\d{4})
    

    And get date, month and year from group1, group2 and group3

    Regex Demo

    Python code in this way should be,

    import re
    
    s = '01/20/2019 12:34:54'
    m = re.search(r'(\d{2})/(\d{2})/(\d{4})', s)
    if m:
     print([m.group(1), m.group(2), m.group(3)])
    

    Prints,

    ['01', '20', '2019']