正则表达式的.*?是什么意思 和()
展开全部
"."是表示匹配所有character:
(Dot.) In the default mode, this matches any character except a newline. If the
DOTALL flag has been specified, this matches any
character including a newline.
"*"是表示匹配0个或者多个
Causes the resulting RE to match 0 or more repetitions of the preceding RE, as
many repetitions as are possible. ab* will match 'a',
'ab', or 'a' followed by any number of 'b's
“*?”关闭贪婪算法
*?, +?, ??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
'<H1>title</H1>', it will match the entire string, and
not just '<H1>'. 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 '<H1>'.
例子,没有?,会匹配尽量多:
>>> greed_p = re.compile("(a.*?d)")
>>> p = re.compile("(a.*d)")
>>> s="abcdabcd"
>>> print greed_p.findall(s)
['abcd', 'abcd']
>>> print p.findall(s)
['abcdabcd']
>>>
(Dot.) In the default mode, this matches any character except a newline. If the
DOTALL flag has been specified, this matches any
character including a newline.
"*"是表示匹配0个或者多个
Causes the resulting RE to match 0 or more repetitions of the preceding RE, as
many repetitions as are possible. ab* will match 'a',
'ab', or 'a' followed by any number of 'b's
“*?”关闭贪婪算法
*?, +?, ??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
'<H1>title</H1>', it will match the entire string, and
not just '<H1>'. 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 '<H1>'.
例子,没有?,会匹配尽量多:
>>> greed_p = re.compile("(a.*?d)")
>>> p = re.compile("(a.*d)")
>>> s="abcdabcd"
>>> print greed_p.findall(s)
['abcd', 'abcd']
>>> print p.findall(s)
['abcdabcd']
>>>
更多追问追答
追问
好多英文看不懂 我英文好差
追答
直接看例子好了。你这里的?是用来关闭贪婪算法的。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询