1

I am trying to return the date from a longer string. The date could be any weekday, any number with a subscript st, nd, rd, th and the month as 3 string values (Jan, Feb etc).

This is my attempt but I'm getting None. Not sure what I'm missing?

string = 'Times for Saturday 10th Aug'

days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
pat = re.compile(r'^(%s) (\d+)(st|nd|rd|th) (%s)$' %
                 ('|'.join(days), '|'.join(months)))

print(re.match(pat, string))
1
  • ^ means the start of line. What happens when you remove that? Commented Oct 11, 2019 at 0:49

2 Answers 2

1

A caret ^ in a regex and re.match both start matching at the start of the string. Simply remove the caret and use re.search instead.

pat = re.compile(r'(%s) (\d+)(st|nd|rd|th) (%s)$' %
                 ('|'.join(days), '|'.join(months)))

print(re.search(pat, string))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @wjandrea. I want to pass the date string to another call function. It's returning <re.Match object; span=(88, 105), match='Saturday 10th Aug'>. I'm only after Saturday 10th Aug
Cheers. Thanks @wjandrea
1

You should remove the beginning of line character ^ and the end of the line character $, then everything works just fine:

>>> re.findall(r'(%s) (\d+)(st|nd|rd|th) (%s)' %
...                  ('|'.join(days), '|'.join(months)), string)
[('Saturday', '10', 'th', 'Aug')]

And, please, don't call variable string -- it's already used in python.

Comments

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.