Python re.match() 方法用于确定正则表达式是否在字符串的开头匹配。如果找到模式,则返回 match 对象,否则返回 'None'。
与方法 re.search() 不同,re.match() 只检查字符串开头的匹配项。它可用于验证 input 或提取字符串开头的特定模式。
此方法采用正则表达式模式和字符串作为参数。如果模式与字符串的开头匹配,则返回一个 match 对象,其中包含有关匹配项的信息,例如匹配的文本和任何捕获的组。
语法
以下是 Python re.match() 方法的语法和参数 -
re.match(pattern, string, flags=0)
参数
以下是 python re.match() 方法的参数 -
- pattern:要搜索的正则表达式模式。
- string:要在其中搜索的输入字符串。
- flags(可选):这些标志会修改对战内容的行为。这些标志可以使用按位 OR (|) 进行组合。
返回值
如果在字符串中找到模式,则此方法返回 match 对象,否则返回 None。
示例 1
以下是使用 re.match() 方法的基本示例。在此示例中,模式 '你好' 与字符串 '你好, world!' 的开头匹配 -
import re
result = re.match(r'hello', 'hello, world!')
if result:
print("Pattern found:", result.group())
else:
print("Pattern not found")
输出
Pattern found: hello
示例 2
在这个例子中,模式 '\d+-\d+-\d+' 与字符串的开头匹配,并且组用于提取日期组件 -
import re
result = re.match(r'(\d+)-(\d+)-(\d+)', '2022-01-01: New Year')
if result:
print("Pattern found:", result.group())
输出
Pattern found: 2022-01-01
示例 3
在此示例中,命名组用于从字符串的开头提取名字和姓氏 -
import re
result = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'John Doe')
if result:
print("First Name:", result.group('first'))
print("Last Name:", result.group('last'))
输出
First Name: John
Last Name: Doe
Last Name: Doe