我正在学习 python 中的 re 模块。我发现了一些(对我来说)没有意义的东西,我也不知道为什么。这是一个小例子,
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 返回“无”,因为它只查看第一个 匹配项。 * 的 first 匹配是字符串首字母处的 '(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]])
Scan through string looking for the first location where this regular expression produces a match, ...
(source: https://docs.python.org/3/library/re.html#re.Pattern.search)
