我正在学习re
python中的模块。我发现了一些对我而言毫无意义的东西,我也不知道为什么。这是一个小例子,
x=re.compile(r'(ha)*')
c=x.search('the man know how to hahahaha')
print(c.group())#output will be nothing,no error.But i expect "hahahaha"
如果我使用re.compile(r'(ha)?')
,也会发生同样的情况
x=re.compile(r'(ha)?')
c=x.search('the man know how to hahahaha')
print(c.group())#output will be nothing,no error.But i expect "ha".
但是,如果使用re.compile(r'(ha)+')
,
x=re.compile(r'(ha)+')
c=x.search('the man know how to hahahaha')
print(c.group())#output will be `hahahaha`,just as expected.
这是为什么,都没有re.compile(r'(ha)*')
和re.compile(r'(ha)+')
在这种情况下一样吗?
模式r'h+'
和r'h*'
不相同,这就是为什么它们不提供相同结果的原因。+
表示您的模式有1个或多个匹配项,*
零个或多个匹配项:
re.search
返回“ nothing”,因为它只看第一场比赛。第一个匹配项*
是'(ha)'
模式在字符串的第一个字母处出现零:
import re
x=re.compile(r'(ha)*')
c=x.findall('the man know how to hahahaha') # get _all_ matches
print(c)
输出:
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'ha', '']
# t h e m a n k n o w h o w t o hahahaha
*
和?
量词允许0个匹配项
组织:
Pattern.search(string [,pos [,endpos]])
扫描字符串以查找该正则表达式产生匹配项的第一个位置,...
(来源:https : //docs.python.org/3/library/ re.html#re.Pattern.search)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句