正则表达式替换指定字符串的方法是使用sub()
函数。sub()
函数用于替换字符串中匹配正则表达式的部分。
语法如下:
re.sub(pattern, repl, string, count=0, flags=0)
参数说明:
-
pattern
: 要搜索的正则表达式模式。 -
repl
: 替换的字符串。 -
string
: 要进行替换操作的原始字符串。 -
count
: 可选参数,指定替换的次数。默认为0,表示替换所有匹配的部分。 -
flags
: 可选参数,用于修改正则表达式的匹配模式。
示例代码:
import re string = "Hello, world!" pattern = "world" replacement = "Python" new_string = re.sub(pattern, replacement, string) print(new_string)
输出结果为:
Hello, Python!
以上代码中,re.sub()
函数将原始字符串中匹配正则表达式模式"world"的部分替换为"Python"。