当前位置:嗨网首页>书籍在线阅读

11-用星号匹配零次或多次

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

7.3.4 用星号匹配零次或多次

* (星号)意味着“匹配零次或多次”,即星号之前的分组可以在文本中出现任意次。它可以完全不存在,也可以一次又一次地重复。让我们再来看看Batman的例子:

>>> batRegex = re.compile(r'Bat(wo)*man')
>>> mo1 = batRegex.search('The Adventures of Batman')
>>> mo1.group()
'Batman'
>>> mo2 = batRegex.search('The Adventures of Batwoman')
>>> mo2.group()
'Batwoman'
>>> mo3 = batRegex.search('The Adventures of Batwowowowoman')
>>> mo3.group()
'Batwowowowoman'

对于 'Batman' ,正则表达式的 (wo)* 部分匹配 wo 的零个实例。对于 'Batwoman',(wo)* 匹配 wo 的一个实例。对于 'Batwowowowoman',(wo)* 匹配 wo 的4个实例。

如果需要匹配真正的星号字符,就在正则表达式的星号字符前加上倒斜杠,即 \*