1

I have a program in which the user can enter a string and have the date in the string. I am using RegEx to match \d+\/\d+\/\d+ to extract the date from the string but for some reason in my test case, only the last entry is able to work

import datetime
import re
dateList = []
dates = ["Foo (8/15/15) Bar", "(8/15/15)", "8/15/15"]
reg = re.compile('(\d+\/\d+\/\d+)')
for date in dates:
    matching = reg.match(date)
    if matching is not None:
        print date, matching.group(1)
    else:
        print date, "is not valid date"

returns

Foo (8/15/15) Bar is not valid date
(8/15/15) is not valid date
8/15/15 8/15/15

Is there something wrong with my RegEx? I tested it with RegEx101.com and it seemed to work fine

1
  • unless you want to learn regexp, I suggest you use dateutil's parser Commented Aug 13, 2015 at 20:14

2 Answers 2

1

if you are looking for a partial match of the regex, use search:

import datetime
import re
dateList = []
dates = ["Foo (8/15/15) Bar", "(8/15/15)", "8/15/15"]
reg = re.compile('([0-9]+/[0-9]+/[0-9]+)')
for date in dates:
    matching = reg.search(date)  # <- .search instead of .match
    if matching is not None:
        print( date, matching.group(1) )
    else:
        print( date, "is not valid date" )
Sign up to request clarification or add additional context in comments.

1 Comment

Please note \d is not an alias for [0-9] in Unicode mode, which is the default. See my answer for more context.
1

You are looking for search(), not match().

date_re = re.compile('([0-9]{2})/([0-9]{2})/([0-9]{2})')
e = date_re.match('foo 01/02/13')
# e is None
e = date_re.search('foo 01/02/13')
# e.groups() == ('01', '02', '13')

Do not use \d where you expect the ASCII 0-9 digits because there are many strange things matched by the Unicode version of \d.

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.