Python中正则表达式的函数使用方法
正则表达式是一种强大的字符串处理工具,Python中提供了re模块可以进行正则表达式的操作。在使用Python中的正则表达式时,一般需要用到如下的几个函数:match、search、findall、sub、split。
1. match函数
match函数是从字符串的起始位置开始匹配,如果匹配成功,返回一个Match对象;如果匹配失败,返回None。match函数的使用方法如下:
re.match(pattern, string, flags=0)
其中,pattern表示正则表达式,string表示要匹配的字符串,flags表示正则表达式的标志位。当没有使用flags时,可以省略该参数。
示例代码:
import re
pattern = r'hello'
string = 'hello world'
result = re.match(pattern, string)
print(result)
输出结果:
<re.Match object; span=(0, 5), match='hello'>
2. search函数
search函数是在整个字符串中搜索,如果匹配成功,返回一个Match对象;如果匹配失败,返回None。search函数的使用方法如下:
re.search(pattern, string, flags=0)
示例代码:
import re
pattern = r'world'
string = 'hello world'
result = re.search(pattern, string)
print(result)
输出结果:
<re.Match object; span=(6, 11), match='world'>
3. findall函数
findall函数是在整个字符串中搜索,返回一个列表,其中包含所有匹配的字符串。findall函数的使用方法如下:
re.findall(pattern, string, flags=0)
示例代码:
import re
pattern = r'\d+'
string = 'The price of the book is $25.99, and the price of the pen is $2.5.'
result = re.findall(pattern, string)
print(result)
输出结果:
['25', '99', '2', '5']
4. sub函数
sub函数是用来替换匹配的字符串,返回替换后的字符串。sub函数的使用方法如下:
re.sub(pattern, repl, string, count=0, flags=0)
其中,pattern表示正则表达式,repl表示替换的字符串,count表示替换的次数,flags表示正则表达式的标志位。当没有使用flags时,可以省略该参数。
示例代码:
import re
pattern = r'\d+'
string = 'The price of the book is $25.99, and the price of the pen is $2.5.'
repl = '***'
result = re.sub(pattern, repl, string)
print(result)
输出结果:
The price of the book is $***.**, and the price of the pen is $*.*.
5. split函数
split函数是用正则表达式来分割字符串,返回一个列表,其中包含分割后的字符串。split函数的使用方法如下:
re.split(pattern, string, maxsplit=0, flags=0)
其中,pattern表示正则表达式,maxsplit表示分割的次数,flags表示正则表达式的标志位。当没有使用flags时,可以省略该参数。
示例代码:
import re
pattern = r'[^\w]+'
string = 'hello, world!'
result = re.split(pattern, string)
print(result)
输出结果:
['hello', 'world', '']
