如何使用Python内置的正则表达式函数匹配字符串
正则表达式是一种用于匹配字符串的语言,常用于文本搜索和替换。Python内置了re模块,它提供了各种用于正则表达式操作的函数。下面介绍如何使用Python内置的正则表达式函数匹配字符串。
1. import re
在使用re模块前需要先引入它,该行代码为:import re
2. re.match()
re.match()用于从字符串的起始位置匹配一个正则表达式。如果匹配成功,match()方法返回一个匹配对象;如果匹配失败,返回None。例如:
import re
str = "hello world"
matchObj = re.match(r'hello', str)
if matchObj:
print("Match obj:", matchObj.group())
else:
print("No match found")
运行结果为:Match obj: hello
3. re.search()
re.search()方法用于在字符串中搜索匹配的正则表达式。只要在字符串中存在匹配该正则表达式的部分,search()就返回一个匹配对象。例如:
import re
str = "hello world"
searchObj = re.search(r'world', str)
if searchObj:
print("Match obj:", searchObj.group())
else:
print("No match found")
运行结果为:Match obj: world
4. re.findall()
re.findall()方法返回所有与正则表达式匹配的字符串列表。例如:
import re
str = "I have 2 cats and 3 dogs."
matchObj = re.findall(r'\d+', str)
print(matchObj)
运行结果为:['2', '3']
5. re.sub()
re.sub()方法用于替换字符串中所有匹配正则表达式的子串。例如:
import re
str = "I have an apple"
subObj = re.sub(r'an', 'a', str)
print(subObj)
运行结果为:I have a apple
以上是Python内置的几个常用的正则表达式函数,配合正则表达式的语法规则,可以方便地对字符串进行匹配、替换等操作。
