python18 正则表达式




正则表达式 re.match(),re.search(),re.findall(),re.sub(),re.split() 元字符 具有特殊意义的专用字符 导入模块 improt re
代码
- '''
- 正则表达式 re.match(),re.search(),re.findall(),re.sub(),re.split()
- 元字符 具有特殊意义的专用字符
- 导入模块
- improt re
- '''
- import re
-
- pattern = '\d\.\d+' # +限定符, \d 0-9 数字出现1次或多次
- s = 'I study Python 3.11 every day'
- # 从字符串的开始位置进行匹配,如果起始位置匹配成功,成功为match对象,否则为None
- # re.match(匹配规则,等匹配字符串,re.I 忽略大小写)
- match = re.match(pattern,s,re.I)
- print(match) #None
- s2 = '3.11Python I study every day'
- match2 = re.match(pattern,s2,re.I)
- print(match2) #<re.Match object; span=(0, 4), match='3.11'> 找到结果了
- # 获取数据
- print('匹配值的起始位置:',match2.start())
- print('匹配值的结束位置:',match2.end())
- print('匹配区间的位置元素:',match2.span())
- print('待匹配的字符串:',match2.string)
- print('匹配的数据:',match2.group())
-
- # re.search() 用于在整个字符串中搜索第一个匹配的值,如果匹配成功,结果为match对象,否则为None
- s3 = 'I study Python3.11 every day Python2.7 I love you'
- match3 = re.search(pattern,s3)
- print(f'search()=>{match3}')
-
- s4 = '4.10 I study Python3.11 every day Python2.7 I love you'
- match4 = re.search(pattern,s4)
- print(f'search()=>{match4}')
-
- s5 = 'I study Python every day Python I love you'
- match5 = re.search(pattern,s5)
- print(f'search()=>{match5}')
-
- # re.findall() 用于在整个字符串搜索所有符合正则表达式的值,结果为一个列表类型
- s6 = 'I study Python3.11 every day Python2.7 I love you'
- match6 = re.findall(pattern,s6)
- print(f'findall()=>{match6}')
-
- # re.sub() 用于实现对字符串中指定子串的替换
- pattern = '黑客|破解|反爬'
- s7 = '我想学习Python,想破解一些VIP视频,Python可以实现无底线反爬吗?'
- newS7 = re.sub(pattern,'xxx',s7)
- print(f'sub()替换后:{newS7}')
-
- # re.split() 与字符串的split方法功能相同,都是分隔字符串
- pattern2 = '[?l&]'
- s8 = 'https://www.baidu.com/s?wd=ysj&rsv_spt=1'
- lst = re.split(pattern2,s8)
- print(lst)