Python re.match() 方法
re.match() 是 Python re 模块中用于从字符串开头匹配模式的函数。
如果字符串的开头匹配指定的正则表达式,就返回一个匹配对象;否则返回 None。
单词释义: match 是匹配、符合的意思。
基本语法与参数
re.match() 是一个模块级函数,直接通过 re 模块调用。
语法格式
re.match(pattern, string, flags=0)
参数说明
- pattern:
- 类型:字符串 (str)
- 描述:要匹配的正则表达式模式。
- string:
- 类型:字符串 (str)
- 描述:被匹配的字符串。
- flags:
- 类型:整数 (int, 可选)
- 描述:正则表达式标志。
函数说明
- 返回值: 如果字符串开头匹配,返回
match对象;否则返回None。 - 注意:
re.match()只从字符串开头匹配,不会扫描字符串中间的部分。
实例
让我们通过例子掌握 re.match() 的用法。
示例 1:基础用法 - 开头匹配
实例
import re
text = "Python是一门强大的编程语言"
# 从开头匹配 "Python"
result = re.match(r'Python', text)
if result:
print("匹配成功:", result.group())
print("匹配位置:", result.start(), "-", result.end())
text = "Python是一门强大的编程语言"
# 从开头匹配 "Python"
result = re.match(r'Python', text)
if result:
print("匹配成功:", result.group())
print("匹配位置:", result.start(), "-", result.end())
运行结果预期:
匹配成功: Python 匹配位置: 0 - 6
示例 2:开头不匹配的情况
实例
import re
text = "我是Python"
# 从开头匹配 "Python" - 会失败
result = re.match(r'Python', text)
if result:
print("匹配成功:", result.group())
else:
print("匹配失败: 字符串开头不是Python")
text = "我是Python"
# 从开头匹配 "Python" - 会失败
result = re.match(r'Python', text)
if result:
print("匹配成功:", result.group())
else:
print("匹配失败: 字符串开头不是Python")
运行结果预期:
匹配失败: 字符串开头不是Python
示例 3:匹配字符串开头后跟内容
实例
import re
text = "2024年是一个特别的年份"
# 匹配年份格式 (4位数字)
result = re.match(r'\d{4}', text)
if result:
print("匹配到年份:", result.group())
text = "2024年是一个特别的年份"
# 匹配年份格式 (4位数字)
result = re.match(r'\d{4}', text)
if result:
print("匹配到年份:", result.group())
运行结果预期:
匹配到年份: 2024
示例 4:使用分组提取数据
实例
import re
text = "Hello World"
# 匹配 "Hello" 后跟空格和 "World"
result = re.match(r'(Hello) (World)', text)
if result:
print("完整匹配:", result.group())
print("第1组:", result.group(1))
print("第2组:", result.group(2))
text = "Hello World"
# 匹配 "Hello" 后跟空格和 "World"
result = re.match(r'(Hello) (World)', text)
if result:
print("完整匹配:", result.group())
print("第1组:", result.group(1))
print("第2组:", result.group(2))
运行结果预期:
完整匹配: Hello World 第1组: Hello 第2组: World
Python re 模块
点我分享笔记