在 Python 中,您可以使用 re
模块来执行正则表达式替换
import re
def regex_replace(pattern, replacement, text):
return re.sub(pattern, replacement, text)
# 用法示例
text = "Hello, World! I am learning Python regex."
pattern = r"regex"
replacement = "regular expressions"
result = regex_replace(pattern, replacement, text)
print(result) # 输出: Hello, World! I am learning Python regular expressions.
在上面的示例中,我们定义了一个名为 regex_replace
的函数,该函数接受三个参数:pattern
(正则表达式模式),replacement
(要替换的字符串)和 text
(要执行替换操作的文本)。然后,我们使用 re.sub
函数来执行正则表达式替换,并返回结果。
领取专属 10元无门槛券
手把手带您无忧上云