re.match函数
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
re.match(pattern, string, flags=0)
#re模块
import re
print(re.match('www', 'www.baidu.com www').span()) # 在起始位置匹配
print(re.match('www', 'www.baidu.com www'))
print(re.match('com', 'www.baidu.com com')) # 不在起始位置匹配
#(0, 3)
#<re.Match object; span=(0, 3), match='www'>
#None
#!/usr/bin/python3
import re
line = "Cats are smarter than dogs"
# .* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符
matchObj = re.match( '(.*) are (.*?) .*', line, re.M|re.I)
print(matchObj)
if matchObj:
print ("matchObj.group() : ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
print ("matchObj.group(0) : ", matchObj.group(0))
print ("matchObj.groups() : ", matchObj.groups())
print ("matchObj.groups(1) : ", matchObj.groups(1))
print ("matchObj.groups(3) : ", matchObj.groups(3))
else:
print ("No match!!")
'''<re.Match object; span=(0, 26), match='Cats are smarter than dogs'>
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
matchObj.group(0) : Cats are smarter than dogs
matchObj.groups() : ('Cats', 'smarter')
matchObj.groups(1) : ('Cats', 'smarter')
matchObj.groups(3) : ('Cats', 'smarter')'''
re.search方法
re.search 扫描整个字符串并返回第一个成功的匹配。
re.search(pattern, string, flags=0)
#!/usr/bin/python3
import re
print(re.search('www', 'www.baidu.com').span()) # 在起始位置匹配
print(re.search('com', 'www.baidu.com').span()) # 不在起始位置匹配
#(0, 3)
#(10, 13)
#!/usr/bin/python3
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
print(searchObj)
if searchObj:
print ("searchObj.group() : ", searchObj.group())
print ("searchObj.group(1) : ", searchObj.group(1))
print ("searchObj.group(2) : ", searchObj.group(2))
else:
print ("Nothing found!!")
'''<re.Match object; span=(0, 26), match='Cats are smarter than dogs'>
searchObj.group() : Cats are smarter than dogs
searchObj.group(1) : Cats
searchObj.group(2) : smarter'''
检索和替换
Python 的re模块提供了re.sub用于替换字符串中的匹配项。