快捷搜索: 王者荣耀 脱发

Python进阶之路 正则表达式之--用问号实现可选匹配

用问号实现可选匹配

有时候,想匹配的模式是可选的。就是说,不论这段文本在不在,正则表达式都会认为匹配。字符?表明它前面的分组在这个模式中是可选的。

import re

batregex = re.compile(rBat(wo)?man)
mo = batregex.search(The Adventures of Batman)
print(mo.group())

mo1 = batregex.search(The Adventures of Batwoman)
print(mo1.group())

输出结果:

Batman
Batwoman

正则表达式中的(wo)?部分表明,wo是可选的分组。该正则表达式匹配的文本中,wo将出现零次或一次。这就是为什么正则表达式即匹配Batman,又匹配Batwoman。

利用前面电话号码的例子,你可以让正则表达式寻找包含区号或不包含区号的电话号码。

import re

phoneregex = re.compile(r(ddd-)?ddd-dddd)

mo = phoneregex.search(My number is 400-555-8888)

print(mo.group())

mo1 = phoneregex.search(My number is 555-9999)
print(mo1.group())

输出结果:

400-555-8888
555-9999

你可以认为?是在说,“匹配这个问号之前的分组零次或一次”。如果需要匹配真正的问号字符,就使用转义字符?。

经验分享 程序员 微信小程序 职场和发展