[英]Pattern matching in Python Regex
例如,對於可變日期,我的輸入可以是星期一或星期一,星期二或星期一,..星期五。我正嘗試在python中使用正則表達式來提供一個模式並檢查其輸入。
result = re.compile(r'\([S|M|T|W|Th|F|Sa]\)|\([S|M|T|W|Th|F|Sa],[S|M|T|W|Th|F|Sa]+\)')
day = "(T,Th)"
if result.match(day):
print "matched"
else:
print 'not'
如果給定的輸入是(T,Th,F)或(T,Th,F,Sa)怎么辦? 我應該如何處理我的模式以處理此類輸入? 有什么解決方案,所以不會冗長嗎?
沒有正則表達式的答案是:
week = ["S", "M", "T", "W", "Th", "F", "Sa"]
days = "(T,Th,C)"
no_match = False
for day in days[1:-1].split(","): #split separates your days-string, [1:-1] removes brackets
if day not in week:
no_match = True
break
if no_match:
print "not"
else:
print "matched"
[1:-1]是切片符號,基本上它會創建一個字符串,該字符串從索引為1(=第2個字符)的字符開始,到倒數第二個字符結束。 實際上,它除去了括號。
使用此正則表達式:
\((S|M|T|W|Th|F|Sa)(,\s*(S|M|T|W|Th|F|Sa))*\)
(S|M|T|W|Th|F|Sa)
匹配任何工作日。 注意使用圓括號而不是方括號,因為它們表示字符類(請參見Ashwini Chaudhary的評論)
這將匹配,例如:
(M, T, W)
(M)
(T, Sa, Fr)
(T,M,Th)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.