3、Python中的数量词默认是贪婪的,总是尝试匹配尽可能多的字符;非贪婪的则相反,总是尝试匹配尽可能少的字符(例如:正则表达式"ab*"如果用于查找"abbbc",将找到"abbb";而如果使用非贪婪的数量词"ab*?",将找到"a"。);
4、与大多数编程语言相同,正则表达式里使用""作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r""表示。
>>> import re
>>> pattern = re.compile('python') # compile将字符串当做正则表达式来编译
>>> result = pattern.search('hello python!')
>>> result
<_sre.SRE_Match object; span=(6,12),match='python'>
>>> result.group()
'python'
>>>
>>> # match方法
>>> result = re.match('a','abc') # match是从字符串的开头开始匹配
>>> result
<_sre.SRE_Match object; span=(0,1),match='a'>
>>> result.group() # 并不直接返回匹配成功的字符串,需要使用group()方法
'a'
>>> result = re.match('a','dabc')
>>> result
>>> result.group() # 没有匹配成功
Traceback (most recent call last):
File "<pyshell#6>",line 1,in <module>
result.group()
AttributeError: 'NoneType' object has no attribute 'group'
>>>
>>> # search方法
>>> result = re.search('python','abcpythondef') # 在字符串的全文中搜索匹配一次,同样也不会直接返回匹配成功的字符串
>>> result
<_sre.SRE_Match object; span=(3,9),match='python'>
>>> result.group()
'python'
>>>
>>> # findall方法
>>> result = re.findall('python','abc python def python ghi')
>>> result
['python','python']
>>> # sub方法
>>> result = re.sub('c','z','click',1) # 使用匹配成功的字符串替换成指定的字符串,参数依次为正则表达式,匹配成功后要去替换的字符串,原字符串,替换次数
>>> result # 返回替换后的字符串
'zlick'
>>> def sub_no_use_match(match_obj): # 用不到模式对象match_obj,但是该函数必须有这个参数
return '36'
>>> re.sub(r'd+',sub_no_use_match,'Python27') # 以函数返回的字符串替换匹配成功的字符串
'Python36'
>>> def sub_use_match(match_obj): # 使用模式对象match_obj来返回最终的字符串
return match_obj.group() + 'hahahaha'
>>> re.sub(r'd+',sub_use_match,'Python27')
'Python27hahahaha'
>>>
>>> # split方法
>>> result = re.split('a','1a2a3a4guyuyun') # 将匹配成功的字符串用作字符串分隔符,返回分隔后的字符串列表
>>> result
['1','2','3','4guyuyun']
>>>
>>> # group和groups方法的区别
>>> result = re.search('(python)python(d{1,3})','pythonpython22')
>>> result.groups() # groups方法是匹配pattern中括号里的格式,以元组的形式返回括号里匹配成功的字符串
('python','22')
>>> result.group() # group是正常的匹配,返回匹配成功的字符串
'pythonpython22'
>>>
>>> string = 'python'
>>> import re
>>> result = re.search(r'(yt)h(o)',string)
>>> result
<_sre.SRE_Match object at 0x000000000293DE88>
>>> result.group()
'ytho'
>>> result.group(0) # 参数0无效
'ytho'
>>> result.group(1) # 从1开始计数
'yt'
>>> result.group(2)
'o'
>>> result.group(1,2)
('yt','o')
>>>
>>> result.groups()
('yt','o')
>>> result.groups(0) # 传入参数无效
('yt','o')
>>> result.groups(1)
('yt','o')
>>>
>>> # finditer方法
>>> string = 'one11python,two22,three33python '
>>> result = re.finditer(r'(d+)(python)',string)
>>> for p in result:
print(p.group())
11python
33python
>>> for p in result:
print(p.group(2))
python
python
>>> for p in result:
print(p.groups()) # 若是pattern中没有括号,则返回的是每个迭代器对应的空元组。
('11','python')
('33','python')