re 是 Python 标准库里的正则表达式模块,提供“查找、替换、分割、匹配”一条龙服务。
re.match() 函数用于从字符串的起始位置匹配正则表达式。如果匹配成功,返回一个匹配对象;否则返回 None。
import repattern = r"hello"text = "hello world"match = re.match(pattern, text)if match: print("匹配成功:", match.group())else: print("匹配失败")# 输出结果# 匹配成功: hellore.search() 函数用于在字符串中搜索正则表达式的第一个匹配项。与 re.match() 不同,re.search() 不要求匹配从字符串的起始位置开始。
import repattern = r"world"text = "hello world"match = re.search(pattern, text)if match: print("匹配成功:", match.group())else: print("匹配失败")#输出结果#匹配成功: worldPython re模块:
https://www.runoob.com/python3/python-re.html