狼语
春芽
共回答了22个问题采纳率:90.9% 举报
+是指.能匹配的字符,出现至少一次.这里的?,你说错了.是取消贪婪算法的.+?可以认为“.”匹配上一次.
*?, +?, ?
The "*", "+", and "?" qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE is matched against 'title', it will match the entire string, and not just ''. Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only ''.
还是看例子吧
>>> kk = re.match('(w.+?)', 'hi all')
>>> kk.groups()
('hi',)
>>> kk = re.match('(w.+)', 'hi all')
>>> kk.groups()
('hi all',)
>>>
可以认为w匹配上h,.可以匹配h后面的字符,+是指.匹配到的数目至少是1个.对于没有?的情况,.+就会匹配h后所有的字符(至少一个,就是>1).有?的时候,就是取消贪婪算法(匹配尽量多),.+匹配上i之后,就不再进行后面的匹配.
所以结果分别是“hi”和“hi all”
1年前
7