Python re 模块
Python 的 re 模块是用于处理正则表达式的标准库模块。
正则表达式(Regular Expression,简称 regex 或 regexp)是一种强大的工具,用于匹配、搜索和操作文本。
通过 re 模块,你可以在 Python 中使用正则表达式来处理字符串。
为什么使用 re 模块?
在处理文本时,我们经常需要查找特定的模式或替换某些字符。例如,验证电子邮件地址、提取网页中的链接、或者格式化文本。手动编写代码来完成这些任务可能会非常繁琐,而正则表达式提供了一种简洁且高效的方式来解决这些问题。
re 模块的基本用法
1. 导入 re 模块
在使用 re 模块之前,首先需要导入它:
import re
2. 常用的 re 模块函数
2.1 re.match()
re.match() 函数用于从字符串的起始位置匹配正则表达式。如果匹配成功,返回一个匹配对象;否则返回 None。
实例
import re
pattern = r"hello"
text = "hello world"
match = re.match(pattern, text)
if match:
print("匹配成功:", match.group())
else:
print("匹配失败")
输出:
匹配成功: hello
2.2 re.search()
re.search() 函数用于在字符串中搜索正则表达式的第一个匹配项。与 re.match() 不同,re.search() 不要求匹配从字符串的起始位置开始。
实例
import re
pattern = r"world"
text = "hello world"
match = re.search(pattern, text)
if match:
print("匹配成功:", match.group())
else:
print("匹配失败")
输出:
匹配成功: world
2.3 re.findall()
re.findall() 函数用于查找字符串中所有与正则表达式匹配的子串,并返回一个列表。
实例
import re
pattern = r"\d+"
text = "There are 3 apples and 5 oranges."
matches = re.findall(pattern, text)
print("找到的数字:", matches)
输出:
找到的数字: ['3', '5']
2.4 re.sub()
re.sub() 函数用于替换字符串中与正则表达式匹配的部分。
实例
import re
pattern = r"apple"
text = "I have an apple."
new_text = re.sub(pattern, "banana", text)
print("替换后的文本:", new_text)
输出:
替换后的文本: I have an banana.
正则表达式的基本语法
1. 普通字符
普通字符(如字母、数字)直接匹配它们自身。
实例
import re
pattern = r"cat"
text = "The cat is on the mat."
match = re.search(pattern, text)

最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



