2

I am setting up a function in Python to receive a date in the format MM/DD/YYYY, then validate it with a regular expression. This is what I have right now:

def getdate():
    date = raw_input("Please enter the date completed (MM/DD/YYY): ")
    if re.match(r"\d{2}/\d{2}/\d{4}", date)
        break
    else:
        print "Incorrect date format"
        getdate()

The system keeps returning a syntax error pointing at the close parentheses in the "if" line. I can't seem to figure out exactly what it is considering a syntax error. I have also tried this with no success:

def getdate():
    date = raw_input("Please enter the date completed (MM/DD/YYY): ")
    valid = "(\d{2}/\d{2}/\d{4})"
    if re.match(valid, date)
        break
    else:
        print "Incorrect date format"
        getdate()

This also returns the same error.

Thanks.

2 Answers 2

2

You're missing the colon:

if re.match(r"\d{2}/\d{2}/\d{4}", date):  # <-- colon needs to be here

P.S: Please don't use recursion to ask for repetitive inputs. You might end up blowing the stack. Better use a loop. Also, devise some way to allow users only a certain number of attempts, to avoid the infinite loop.

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

1 Comment

I cannot believe I missed that.... That is embarrassing. Thank you. It never fails to have someone else look at your code... Thanks for the suggestion too. I see what you mean. I will fix that.
1

You need a colon at the end:

if re.match(r"\d{2}/\d{2}/\d{4}", date):
#                               here --^

Python uses colons to end statements.

Also, as @RohitJain stated, using recursion to ask for repeated input is bad practice. You might want to make your code like this:

def getdate():
    date = raw_input("Please enter the date completed (MM/DD/YYY): ")
    valid = "(\d{2}/\d{2}/\d{4})"
    while not re.match(valid, date):
        print "Incorrect date format"
        date = raw_input("Please enter the date completed (MM/DD/YYY): ")
    return date

This new code uses a loop that runs until the input meets the specifications (namely, re.match returns with a match).

1 Comment

Oh thank you very much for the suggestion! Using a while loop vice an if statement is genius!

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.