正则表达式的元字符?,有两种用法。
第一种,表示前面的项是可选项,可有可无,就是匹配零到一次。
第二种,用在花括号后面,表示非贪心匹配。
当?用在花括号后面时,就不是第一种意义。不是表示花括号可有可无,而是表示非贪心匹配。
例1:
以下的正则表达式匹配one和done
>>> batRegex = re.compile(r'd?one')
>>> mo=batRegex.search('my one yes')
>>> mo.group()
'one'
>>> mo=batRegex.search('done yes')
>>> mo.group()
'done'
例2:
?前面也可以是圆括号界定的项。
>>>phoneRegex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
>>>mo1 = phoneRegex.search('My number is 415-555-4242')
>>>mo1.group()
’415-555-4242‘
>>>mo2 = phoneRegex.search('My number is 555-4242')
>>>mo2.group()
'555-4242'
例3:
在字符串'HaHaHaHaHa1中,因为(Ha){3,5}可以匹配3个、4个或5个实例,Match对象的group()调用会返回'HaHaHaHaHa',而不是更短的可能结果。毕 竟,'HaHaHa'和'HaHaHaHa'也能够有效地匹配正则表达式(Ha){3,5}。
Python的正则表达式默认是“贪心”的,这表示在有二义的情况下,它们会尽可能匹配最长的字符串。花括号的“非贪心”版本匹配尽可能最短的字符串,即在结束的花括号后跟着一个问号。
>>>greedyHaRegex = re.compile(r'(Ha){3,5}')
>>>mo1 = greedyHaRegex.search('HaHaHaHaHa')
>>>mo1.group()
'HaHaHaHaHa'
>>>nongreedyHaRegex = re.compile(r'(Ha){3,5}?')
>>>mo2 = nongreedyHaRegex.search('HaHaHaHaHa')
>>>mo2.group()
'HaHaHa'
网友评论