Python正则表达式中的模式匹配
例如,我对variable day的输入可以是星期一或星期一、星期二或星期一、…、星期五,我试图在python中使用正则表达式来提供一个模式并检查其输入Python正则表达式中的模式匹配,python,regex,Python,Regex,例如,我对variable day的输入可以是星期一或星期一、星期二或星期一、…、星期五,我试图在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
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),该怎么办?我应该如何处理我的模式来处理这些类型的输入?有没有什么解决方案可以让它不会太长?没有regex的答案是:
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)
[]
表示,|
不是或操作。使用(S | M | T | W | Th | F | Sa)
。@user3226156基本上不包括第一个和最后一个字符。在他的例子中,只包括T,Th,C
。我明白了,这就是“*”的用法。@user3226156是的,没错。它的意思是“零或更多”。