我们需要 正则表达式+re模块 对字符串进行详细匹配、替换等操作。

正则表达式:

python : 正则表达式与re模块_正则表达式

re模块中常用语法:

python : 正则表达式与re模块_正则表达式_02

(1)匹配 re.match ( )

import re
pattern ='\d\.\d+'  # '\d'表示单个数字 ; '\.'用于匹配'.'其中'\'为转译字符 ; '\d+'表示匹配一次或多次数字

str1 = 'I study python2.7 and python3.11 every day'
match1 = re.match(pattern,str1,re.I) # re.I 表示ignore,忽略大小写进行匹配
print(match1)  # None ,因为re.match()从开始位置匹配

str2 = '2.7python and 3.11python I study every day'
match2 = re.match(pattern,str2,re.I)
print(match2)  # <re.Match object; span=(0, 3), match='2.7'>,返回了一个match对象

# 输出match对象的各个部分
print('匹配值的起始位置:',match2.start())  # 匹配值的起始位置: 0
print('匹配值的结束位置:',match2.end())  # 匹配值的结束位置: 3
print('匹配区间:',match2.span())  # 匹配区间: (0, 3)
print('匹配值:',match2.group())  # 匹配值: 2.7
print('所匹配的原字符串:',match2.string)  # 所匹配的原字符串: 2.7python and 3.11python I study every day
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

(2)单个搜索 re.search ( ) 和 全部搜索 re.findall ( )

import re
pattern ='\d\.\d+'
str1 = 'I study python2.7 and python3.11 every day'

# 单个搜索 re.search( )仅仅能搜索到第一个匹配的值
match1 = re.search(pattern,str1)
print(match1)  # <re.Match object; span=(14, 17), match='2.7'>,只有2.7
print(match1.group())  # 2.7, re.search( )返回的同样是match对象,也可以用.group()

# 全部搜索 re.findall ( )返回的是列表类型
lst1 = re.findall(pattern,str1)
print(lst1)  # ['2.7', '3.11']
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

(3)替换 re.sub ( )

import re
pattern = '黑客|泄露|邪教'
s = '邪教组织雇佣了一批黑客攻击网站,泄露了大量敏感信息'

new_s1 = re.sub(pattern,'*',s)
print(new_s1)  # *组织雇佣了一批*攻击网站,*了大量敏感信息

new_s2 = re.sub(pattern,'*',s,count=2)  # count表示替换的最大次数,默认为0(全部替换)
print(new_s2)  # *组织雇佣了一批*攻击网站,泄露了大量敏感信息
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

(4)分隔 re.split ( )

import re
pattern = '://|:|/'
url = 'https://www.example.com:8080/path'  # 协议://域名:端口/路径
lst = re.split(pattern,url)
print(lst)  # ['https', 'www.example.com', '8080', 'path']
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.