1、匹配字符串中任意由两个英文字母和四个数字组成的字符串,并将英文和数字分开变为元组形式
pat = re.compile('([a-zA-Z]{2})([0-9]{4})')
# 例如:
s1 = 'sf2134dsfs32dsfdfs3421fsdf'
s2 = re.findall(pat, s1)
print(s2)
print(type(s2[0]))
# 运行结果:
# [('sf', '2134'), ('fs', '3421')]
# <class 'tuple'>
2、获取路径中包含的某个中间路径之后的内容
pat2 = re.compile('(?<=/yourmidpath).*$')
# 例如:
path = 'D:/test/yourmidpath/needpathorfile'
s1 = re.findall(pat2, path)
print(s1)
# 运行结果
['/needpathorfile']
3、匹配任意多个空格
pat3 = re.compile(r' +')
s1 = '前 后'
s2 = re.sub(' +', ' ', s1)
print(s2)
# 运行结果:
前 后
4、以分号或冒号切割文本
cutcon = re.split(':|;|:|;', con)
5、匹配任意字符加不同标点前面的内容
pat4 = re.compile(r"(.*?)任意字符[,|,]")
s1 = '需要的内容任意字符,'
s2 = re.findall(pat4, s1)
print(s2)
运行结果:
['需要的内容']
