#Python正则表达式代码示例
##使用match()方法匹配字符串,从字符串起始部分对模式进行匹配。成功返回一个匹配对象,否则返回None,匹配对象的group()方法能够用户显示那个成功的匹配
import re
m=re.match('foo','foo')#模式匹配字符串
if m is not None:#如果匹配成功,就输出匹配内容
m.group()
m#确认返回的匹配对象
<_sre.SRE_Match object; span=(0, 3), match='foo'>
m.group()
'foo'
#如下是一个失败的匹配,它返回None
m=re.match('foo','bar')#模式并不能匹配字符串
if m is not None:m.group()#单行版本的if语句
#如果没有if语句,会出现AttributeError异常(None是返回值,并没有group()属性【方法】)
m=re.match('foo','food on the table')#匹配成功,尽管字符串比模式要长,但从字符串的起始位置开始匹配就会成功
m.group()
'foo'
##使用search()在一个字符串中查找模式(搜索与匹配的对比)
match()和search()不同在于match()试图从字符串的其实部分开始匹配模式,而search()可以从任意位置开始匹配
m=re.match('foo','seafood')#匹配失败 试图将模式中的'f'匹配到字符串的首字母's'上
if m is not None:
m.group()
m=re.search('foo','seafood')#使用search()代替
if m is not None:m.group()
m.group()
'foo'
##匹配多个字符串
bt='bat|bet|bit' #正则表达式模式:bat、bet、bit
m=re.match(bt,'bat') #'bat'是一个匹配
m.group()
'bat'
m=re.match(bt,'blt') #对'blt'没有匹配
# m.group()#匹配失败,
print(m)
None
m=re.match(bt,'He bit me!') #不能匹配字符串
if m is not None:m.group()
m=re.search(bt,'He bit me!')#通过搜索查找'bit'
m.group()
'bit'
##匹配任何单个字符
点号(.)不能匹配一个换行符\n或者非字符,也就是说,一个空字符串
anyend='.end'
m=re.match(anyend,'bend') #点号匹配'b'
m.group()
'bend'
m=re.match(anyend,'end') #不匹配任何字符
print(m)
None
m=re.match(anyend,'\nend') #除了\n之外的任何字符
print(m)
None
m=re.search('.end','The end.') #在搜索中匹配' '
m.group()
' end'
#下面的示例在正则表达式中搜索一个真正的句号(小数点),通过使用一个反斜线对据点的功能进行转义
patt314='3.14' #表示正则表达式的点号
pi_patt='3\.14' #表示字面量的点号(dec. point)
m=re.match