(1) re.match\re.search
re.match(pattern,string.flag=0) #从第一个字母匹配,span()输出范围
re.search(pattern,string,flags=0) #区别为search搜索整个字符串
(2) re.compile
re.compile(pattern,flag=0)
#用来编辑正则表达式,返回一个正则表达式,用于match和search方法
例子:
import re
pattern = re.compile(r'\d+') #得到新的正则表达式pattern
result = pattern.search("asdf13 34etq 56')
print(result)
>>> <re.Match object; span=(4, 6), match='13'> #注意输出的类型是 re.match 类型
result.group() #group()的用法,作用是分组,groups()的作用是全部分组
>>> '13'
(3)re.findall
re.findall是搜索所有的符合条件的字符串,并返回一个列表
import re
pattern = re.compile(r' \w+\s\w')
result1 = pattern.findall("asdf13 34etq 56") #用法1,用来配合match和search
print(result1)
>>> ['13', '34', '56']
re.findall(string,pos,endpos) #()左封闭,如(0,3)指124
例子:找到字符串里面所有的数字:```
import re
string = 'qwe123 rty456 uio789'
re.findall(r'\d+',string)
>>>['123', '456', '789']
例子:补充!!
(4)替换与补充
re.sub(pattern,replace,string,count=0,flags=0) #作用就是将搜索到的字符串替换为指定的字符串
import re
re.sub(r'\d\d\d','000','123qwe456qwe78ui',count=1)
>>>'000qwe456qwe78ui'
还可以替换为函数,如将字符串中的数字放大两倍,s = ‘A23G4HFD567’
import re
def double():
补充!!!
(5)re.finditer
refinditer(pattern,string,flags=0)的作用是找到字符串,将其作为一个迭代器返回
import re
it = re.finditer(r'\d+','as24jjl453lj6l786l8')
for match in it:
print(match.group())
>>>24
453
6
786
8
(6)re.split
re.split(pattern,string,maxsplit = 0,flags=0)的作用是以搜索到的字符串作为分割符
import re
re.split(r'\w+','runnoob, runnoob.')
>>> ['', ', ', '.']
练习:
(1)用正则表达式匹配IP地址172.20.68.170,191.125.1.1
import re
ip = '192.168.1.1'
trueIp =re.search(r'(([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])\.){3}([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])',ip)
print(trueIp)
>>> 192.168.1.1
'''
这种写法存在问题,即[01]{0,1}\d{0,1}\d会匹配到001的字符出来,而这样是不对的。故换另一种方式
'''
分析:
0~99正则表达式为[0-9]{0,1}\d
100~199表示为 1\d{2}
200~249表示为 2[0-4]\d
250~255表示为 25[0-5]
因此,ip地址的正则表达式为([0-9]{0,1}\d|1\d{2}| 2[0-4]\d|25[0-5].){3}[0-9]{0,1}\d|1\d{2}| 2[0-4]\d|25[0-5]
import re
ip = '192.170.1.1'
re.search(r'([01]{0,1}\d{0,1}\d\.){3}[01]{0,1}\d{0,1}\d',ip)
>>> <re.Match object; span=(0, 11), match='192.170.1.1'>