正则_问号实现可选匹配

2018-08-20  本文已影响0人  测试媛617
import re
batRegex = re.compile(r'Bat(wo)?man')
mo1 = batRegex.search('The Adventures of Batman')
print(mo1.group())
mo2 = batRegex.search('The Adventures of Batwoman')
print(mo2.group())


phone = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
mo3 = phone.search('my phone is 123-456-5678')
print(mo3.group())
mo4 = phone.search('my phone is 456-7890')
print(mo4.group())
结果是:
Batman
Batwoman
123-456-5678
456-7890
上一篇下一篇

猜你喜欢

热点阅读