Python正则表达式中的re.sub函数可以用来替换字符串中满足正则表达式的部分内容。它的使用方法是:re.sub(pattern, repl, string, count=0),其中,pattern是正则表达式,repl是替换的新字符串,string是原字符串,count是替换的次数,如果count=0,则表示替换所有匹配的字符串。
示例
# 将字符串中的字母a替换成字母b import re s = 'python python python' s = re.sub('a', 'b', s) print(s) # 输出:python python python
替换技巧
- 使用正则表达式替换字符串中的某部分内容时,可以使用正则表达式的子表达式,以支持更复杂的替换操作,例如:
import re s = 'python python python' s = re.sub('(p)y(thon)', r'\1\2', s) print(s) # 输出:pythonpythonpython
- 使用正则表达式替换字符串中的某部分内容时,可以使用正则表达式的分组替换,以支持更复杂的替换操作,例如:
import re s = 'python python python' s = re.sub('(p)y(thon)', r'\2\1', s) print(s) # 输出:thonpy python python
- 使用正则表达式替换字符串中的某部分内容时,可以使用正则表达式的反向引用,以支持更复杂的替换操作,例如:
import re s = 'python python python' s = re.sub('(p)y(thon)', r'\2\1\2', s) print(s) # 输出:thonpython pythonpython pythonpython