管道可以匹配多个正则表达式中的一个

>>> 
>>> m=re.search(r'Batman|Tina Fey','Batman and Tina Fey')
>>> print(m.group())
Batman
>>> m=re.search(r'Batman|Tina Fey','Tina Fey and Batman')
>>> print(m.group())
Tina Fey
>>>

  问号表明它前面的字符或分组在这个模式中是可选的,匹配“零次或一次"

>>> batRegex=re.compile(r'Bat(wo)?man')
>>> m1=batRegex.search('I am a Batman')
>>> print(m1.group())
Batman
>>> m2=batRegex.search('I am a Batwoman')
>>> print(m2.group())
Batwoman
>>>


在上述正则表达式中wo是可选的,既可以匹配Batman,又可以匹配Batwoman

>>> 
>>> phoneRegex=re.compile(r'(\d{3}-)?\d{3}-\d{4}')
>>> m1=phoneRegex.search('My phone number is 021-456-2345')
>>> print(m1.group())
021-456-2345
>>> m2=phoneRegex.search('My phone number is 456-2345')
>>> print(m2.group())
456-2345
>>>

上面的正则表达式匹配的电话号码可以带区号,也可以不带区号

  星号意味着“匹配零次或者多次”

>>> 
>>> batRegex=re.compile(r'Bat(wo)*man')
>>> m=batRegex.search('I am a Batman')
>>> print(m.group())
Batman
>>> m=batRegex.search('I am a Batwoman')
>>> print(m.group())
Batwoman
>>> m=batRegex.search('I am a Batwowoman')
>>> print(m.group())
Batwowoman
>>>

  加号意味着“匹配一次或多次”

>>> 
>>> batRegex=re.compile(r'Bat(wo)+man')
>>> m=batRegex.search('I am a Batwoman')
>>> print(m.group())
Batwoman
>>> m=batRegex.search('I am a Batwowoman')
>>> print(m.group())
Batwowoman
>>> m=batRegex.search('I am a Batman')
>>> m == None
True
>>>

  花括号匹配特定次数

(ha){2}匹配‘haha’

(ha){2,}匹配2次或更多次ha

(ha){.2}匹配0到2次ha

(ha){2.5}匹配2到5次ha