2015-05-04 47 views
0

我想知道是否可以在Python中使用re來找到問題的答案。例如,用戶被問到一個問題「你想繼續嗎?」; 我可以使用正則表達式,以便'y''是''是''是''是'將變量設置爲1或'n''否'否''否'將變量設置爲0?我知道不使用正則表達式就可以做到這一點,但我試圖提高我對使用正則表達式的知識。Python正則表達式 - 根據輸入確定答案

+4

儘量增加你的正則表達式的知識,更好的例子。這一個沒用,你不會學習正則表達式的特別之處。 – Maroun

+0

爲什麼不只是例如'{'y','yes'}'中的response.lower()這裏沒有必要使用正則表達式。 – jonrsharpe

回答

1

是的,但正則表達式是矯枉過正這一點。你可以做得更簡單。下面的代碼是爲Python 3.您將取代inputraw_input和修改print聲明爲Python 2

>>> def continue_prompt(): 
...  while True: # Continue prompting until valid answer. 
...   answer = input("Do you want to continue? ") 
...   if answer.lower() in ['y', 'yes']: 
...    cont = True 
...    break 
...   elif answer.lower() in ['n', 'no']: 
...    cont = False 
...    break 
...   else: 
...    print("Please answer yes or no. ", end="") 
...  return cont 
... 
>>> answer = continue_prompt() 
Do you want to continue? foo 
Please answer yes or no. Do you want to continue? y 
>>> assert answer == True 
>>> answer = continue_prompt() 
Do you want to continue? yes 
>>> assert answer == True 
>>> answer = continue_prompt() 
Do you want to continue? NO 
>>> assert answer == False 
>>> answer = continue_prompt() 
Do you want to continue? N 
>>> assert answer == False 
>>> 
+0

謝謝,我只是看到這樣的事情是否可以使用正則表達式,但正如你所說,我想它的矯枉過正。 – hjalpmig

+0

沒問題。我很少使用正則表達式。當我還是一個年輕的Python程序員時(一年前),有人說可以用''in''或字符串'find()'方法完成'regex'的大部分工作。這就是說,有很多用例只有一個正則表達式可以做,所以這是一個很好的工具。 –

4

例如,你可以使用可選組驗證,像這樣:

re.search(r'[yY](?:es)?', user_input) # es is option but requires a y