簡體   English   中英

在Python中的If語句中使用re.match

[英]Using re.match in an If statement in Python

我在Python中設置一個函數來接收MM / DD / YYYY格式的日期,然后用正則表達式驗證它。 這就是我現在所擁有的:

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()

系統不斷返回指向“if”行中的近括號的語法錯誤。 我似乎無法弄清楚它是在考慮語法錯誤。 我也試過這個沒有成功:

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()

這也會返回相同的錯誤。

謝謝。

你錯過了冒號:

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

PS:請不要使用遞歸來要求重復輸入。 你可能會最終吹掉堆棧。 更好地使用循環。 另外,設計一些方法允許用戶只進行一定次數的嘗試,以避免無限循環。

你最后需要一個冒號:

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

Python使用冒號來結束語句。

另外,正如@RohitJain所說,使用遞歸來請求重復輸入是不好的做法。 你可能想要像這樣編寫代碼:

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

這個新代碼使用一個循環,該循環一直運行直到輸入符合規范(即re.match返回匹配)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM