Python中的正则表达式函数使用指南
正则表达式是一种强大而灵活的模式匹配语言,Python通过re模块提供了支持正则表达式的函数,可以用来匹配、替换字符串,切割字符串等。本文将介绍Python中常用的正则表达式函数及其使用方法。
1. re.match(pattern, string, flags=0)
re.match()函数用于尝试从字符串的开头匹配一个模式,如果匹配成功,则返回一个匹配对象,否则返回None。其中,pattern为正则表达式,string为要匹配的字符串,flags为标志位,可以缩写为一个或多个re.A、re.I、re.L、re.M、re.S、re.U、re.X。以下是一个简单的示例代码:
import re
str = "hello123world"
matchObj = re.match(r'hello(.*)world', str, re.M|re.I)
if matchObj:
print("matchObj.group() : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1))
else:
print("No match!!")
输出结果:
matchObj.group() : hello123world
matchObj.group(1) : 123
2. re.search(pattern, string, flags=0)
re.search()函数用于搜索字符串中 次出现的正则表达式模式,如果匹配成功,则返回一个匹配对象,否则返回None。同样,pattern为正则表达式,string为要匹配的字符串,flags为标志位。示例代码如下:
import re
str = "hello123world"
searchObj = re.search(r'hello(.*)world', str, re.M|re.I)
if searchObj:
print("searchObj.group() : ", searchObj.group())
print("searchObj.group(1) : ", searchObj.group(1))
else:
print("Nothing found!!")
输出结果:
searchObj.group() : hello123world
searchObj.group(1) : 123
3. re.findall(pattern, string, flags=0)
re.findall()函数用于查找字符串中所有匹配正则表达式的子串,并返回一个包含所有匹配字符串的列表。同样,pattern为正则表达式,string为要匹配的字符串,flags为标志位。示例代码如下:
import re
str = "hello123world456"
list = re.findall(r'\d+', str)
print(list)
输出结果:
['123', '456']
4. re.sub(pattern, repl, string, count=0, flags=0)
re.sub()函数用于替换字符串中所有匹配正则表达式的子串,并返回替换后的字符串。其中,pattern为正则表达式,repl为替换的字符串,string为要匹配的字符串,count为替换次数的最大值(默认为0表示替换所有匹配字符串),flags为标志位。示例代码如下:
import re
str = "hello123world456"
newStr = re.sub(r'\d+', '', str)
print(newStr)
输出结果:
helloworld
5. re.compile(pattern, flags=0)
re.compile()函数用于将正则表达式编译成对象,以便在后续的操作中重复使用,可以提高整个程序的执行效率。其中,pattern为正则表达式,flags为标志位。示例代码如下:
import re
pattern = re.compile(r'\d+')
str1 = "hello123world456"
str2 = "python456is789great"
list1 = pattern.findall(str1)
list2 = pattern.findall(str2)
print(list1)
print(list2)
输出结果:
['123', '456']
['456', '789']
本文介绍了Python中常用的正则表达式函数及其使用方法,其中re.match()、re.search()、re.findall()、re.sub()是最常用的四个函数,re.compile()可以提高程序的执行效率。熟练掌握这些函数的使用方法,可以方便地处理各种字符串匹配、替换、切割等问题。
