步入正题之前,先来看一下re.sub()函数的功能演示:
import re
text = 'Jame 12 years old'
pattern = r'[A-Z]\w+\s\d{1,2}' # 正则,匹配出名字和年龄
result = re.sub(pattern,'hello',text) # 将匹配出的内容替换为hello
print(text) #打印原来的文本
print(result) # 打印替换后的文本
>>>Jame 12 years old
>>>hello years old
显而易见,pattern从text中匹配到的内容"Jame 12"被中间的字符串即hello替换,记住这三个参数之间的关系,下面开始步入正题。
import re
text = 'Jame 12 years old'
pattern = r'([A-Z]\w+)\s(\d{1,2})'
print(re.search(pattern, text).group(0))
print(re.search(pattern, text).group(1))
print(re.search(pattern, text).group(2))
>>>Jame 12
>>>Jame
>>>12
与文章开头的代码不同的是,这次分别对名字和年龄进行了分组:
名字:([A-Z]\w+)
年龄:(\d{1,2})
可以看到,goup(0)对应的是全部内容,goup(1)对应名字,goup(2)对应年龄,记住这个对应关系!接下来加入一段代码:
result = re.sub(pattern, r'\1 is \2', text)
print(result)
>>>Jame is 12 years old
不知道你是否已经猜到\1\2分别代表什么了呢?其实代表的就是group(1)和group(2),既然中间的参数是准备替换的字符串,那我们同样可以引用已经匹配出来的字符串,对于初学者这里可能比较晕,多练习几遍自然就懂了。