Python re.sub() 方法用于将字符串中出现的模式替换为另一个字符串。它会在输入字符串中搜索模式的所有不重叠匹配项,并将其替换为指定的替换字符串。
此方法有助于使用正则表达式对字符串执行全局搜索和替换操作。它在模式匹配和替换方面提供了灵活性,允许对文本数据进行复杂的转换。
通过 count 和 flags 的可选参数,re.sub() 方法通过使其成为 Python 中文本处理任务的多功能工具,提供了对替换数量和匹配行为的控制。
语法
以下是 Python re.sub() 方法的语法和参数 -
re.sub(pattern, repl, string, count=0, flags=0)
参数
以下是 python re.sub() 方法的参数 -
- pattern:要搜索的正则表达式模式。
- repl:要为每个匹配项调用的替换字符串或函数。
- string:要对其执行替换的输入字符串。
- count(可选):要进行的最大替换数。默认值为 0,表示替换所有匹配项。
- flags(可选):用于修改匹配行为的标志(例如,re.IGNORECASE)
返回值
此方法返回 match 对象的迭代器
示例 1以下是 python re.sub() 方法的基本示例,其中字符串中的所有数字序列都替换为字符串 'number' −
import re
result = re.sub(r'\d+', 'number', 'Welcome to qikepu learning 2024')
print(result)
输出
Welcome to qikepu learning number
示例 2
此示例使用 pattern 和 replacement 字符串中的捕获组来重新排列日期格式。
import re
result = re.sub(r'(\d+)-(\d+)-(\d+)', r'\3/\2/\1', 'Date: 2022-01-01')
print(result)
输出
Date: 01/01/2022
示例 3
在此示例中,函数 'square' 的输出用作替换。它将字符串中找到的每个数字匹配项平方 -
import re
def square(match):
num = int(match.group())
return str(num ** 2)
result = re.sub(r'\d+', square, 'Numbers: 1 2 3 4 5')
print(result)
输出
Numbers: 1 4 9 16 25
示例 4
在此示例中,count=1 参数将替换数限制为 1,因此仅替换第一个数字序列 -
import re
result = re.sub(r'\d+', 'number', 'There are 123 apples and 456 oranges.', count=1)
print(result)
输出
There are number apples and 456 oranges.