欢迎访问宙启技术站
智能推送

Python正则表达式re模块:findall()、sub()、split()函数详解

发布时间:2023-07-04 22:47:57

Python的re模块是用于处理正则表达式的库,其中有几个常用函数:findall()、sub()、split()。下面分别详细介绍这三个函数的使用。

1. findall()函数:

findall()函数用于查找字符串中的所有匹配项,并返回一个列表。它的语法为:

re.findall(pattern, string, flags=0)

其中,pattern为正则表达式的模式,string为要匹配的字符串,flags为匹配模式的标志(可选参数,默认为0)。

示例代码:

import re

 

str1 = "Hello, it is a beautiful day. Hello, how are you?"

pattern = "Hello"

result = re.findall(pattern, str1)

print(result)

输出:['Hello', 'Hello']

在上面的例子中,我们需要查找字符串str1中所有的"Hello",所以正则表达式的模式为"Hello"。输出结果为一个包含两个"Hello"的列表。

2. sub()函数:

sub()函数用于替换匹配到的字符串。它的语法为:

re.sub(pattern, repl, string, count=0, flags=0)

其中,pattern为正则表达式的模式,repl为用于替换匹配字符串的内容,string为要匹配的字符串,count为替换次数(可选参数,默认为0),flags为匹配模式的标志(可选参数,默认为0)。

示例代码:

import re

 

str1 = "Hello, it is a beautiful day. Hello, how are you?"

pattern = "Hello"

repl = "Hi"

result = re.sub(pattern, repl, str1)

print(result)

输出:Hi, it is a beautiful day. Hi, how are you?

在上面的例子中,我们替换了原字符串str1中的所有"Hello"为"Hi",所以正则表达式的模式为"Hello",替换内容为"Hi"。

3. split()函数:

split()函数用于按照正则表达式的模式切割字符串。它的语法为:

re.split(pattern, string, maxsplit=0, flags=0)

其中,pattern为正则表达式的模式,string为要切割的字符串,maxsplit为最大切割次数(可选参数,默认为0,表示切割所有匹配的字符串),flags为匹配模式的标志(可选参数,默认为0)。

示例代码:

import re

 

str1 = "Hello, it is a beautiful day. Hello, how are you?"

pattern = "\W+"

result = re.split(pattern, str1)

print(result)

输出:['Hello', 'it', 'is', 'a', 'beautiful', 'day', 'Hello', 'how', 'are', 'you', '']

在上面的例子中,我们使用正则表达式的模式"\W+"来切割字符串str1,其中"\W+"表示一个或多个非字母、非数字、非下划线的字符。输出结果为一个包含所有切割后的字符串的列表。

总结:以上三个函数分别用于在字符串中查找所有匹配项、替换匹配到的字符串和切割字符串。通过灵活地应用这些函数,可以处理复杂的字符串操作。