1

I would like to match the time string python with python re module. My code is like this:

import re
def match_time(el):
    year = '(?:19|20)[0-9]{2}'
    month = '(?:0?[1-9]|1|[0-2])'
    day = '(?:0?|[1-9]|[1-2][0-9]|3[0-1])'
    hour = '(?:[0-1]?[0-9]|2[0-4])'
    minute = '(?:[0-5]?[0-9])'
    second = '(?:[0-5]?[0-9])'
    sep = '\s?'

    date_pattern = '{year}[/-]{month}[/-]{day}'.format(year=year, month=month, day=day)
    time_pattern = '(?:{sep}{hour}:{minute}:{second})?'.format(sep=sep, hour=hour, minute=minute, second=second)

    p = date_pattern + time_pattern

    m = re.findall(p, el)
    return m

el = '2019/3/23 0:11:01 fxxxxxff fff'

m = match_time(el)
print(m)

The output of this is 2019/3/. What error it is with my code please ? I hope the function can match sentences like both 2019/3/23 0:11:01 fxxxxx ffff and 2019/3/23 fffdddd dddwww, so I added a ? after the time_pattern, but the output is weird. How could I make it work please ?

1 Answer 1

2

In my work, I like to almost always assume Regex is greedy in searching for options. When you give it 0? as the first option, it allows for an empty string (is this what you want? I assume not), and it will select that is the valid solution. So reordering your regex will work.

year = '(?:19|20)[0-9]{2}'
month = '(?:0?[1-9]|1[0-2])'
day = '(?:[1-2][0-9]|3[0-1]|0?[1-9])'
hour = '(?:[0-1]?[0-9]|2[0-4])'
minute = '(?:[0-5]?[0-9])'
second = '(?:[0-5]?[0-9])'
sep = '\s?'

This captures your desired output, though I doubt it is the most efficient method, it varies the least from your own work.

Sign up to request clarification or add additional context in comments.

3 Comments

I found a bug in OP's month regex. Correct value should be month = '(?:0?[1-9]|1[0-2])' . Also, your solution works great!
@AnkurSaxena There really is one, it's really just to be able to use | in an enclosed setting
@AnkurSaxena Thanks for telling me this !!! Would you please add a few lines about what is the most efficient way you mentioned in the answer ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.