{"title":"Python 正则表达式:查找和替换 - 使用 re 模块","description":"学习如何使用 Python 的 re 模块进行正则表达式查找和替换。本文提供示例代码展示如何使用 re.findall 和 re.sub 函数查找匹配模式的子字符串并替换它们。","keywords":"python, 正则表达式, re 模块, 查找, 替换, findall, sub, 代码示例","content":"使用 Python 的 re 模块可以方便地进行正则表达式查找和替换操作。

  1. 查找:

使用 re.findall(pattern, string) 函数可以在字符串 string 中查找所有匹配正则表达式 pattern 的子串,并以列表形式返回。

import re

string = "hello, world! hello, python!"
pattern = "hello"

result = re.findall(pattern, string)
print(result)  # ['hello', 'hello']
  1. 替换:

使用 re.sub(pattern, repl, string) 函数可以将字符串 string 中所有匹配正则表达式 pattern 的子串替换为 repl。

import re

string = "hello, world! hello, python!"
pattern = "hello"
repl = "hi"

result = re.sub(pattern, repl, string)
print(result)  # hi, world! hi, python!

以上是 Python 中使用正则表达式进行查找和替换的基本方法。你可以根据实际情况修改正则表达式 pattern 和替换字符串 repl 来实现不同的功能。


原文地址: https://www.cveoy.top/t/topic/oBmG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录