MST

星途 面试题库

面试题:Python中re模块search函数与match函数的区别

请详细阐述Python的re模块中search函数和match函数在功能、匹配规则以及返回值方面有哪些不同,并分别给出简单示例代码。
27.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

功能区别

  • search函数:在整个字符串中搜索匹配正则表达式的第一个位置。它会扫描整个字符串,一旦找到匹配就停止。
  • match函数:只从字符串的开头开始匹配正则表达式。如果字符串开头不匹配,则返回None。

匹配规则区别

  • search函数:匹配整个字符串内任意位置的内容。
  • match函数:严格要求从字符串的起始位置开始匹配。

返回值区别

  • search函数:如果找到匹配,返回一个Match对象,该对象包含了匹配的相关信息,如匹配的内容、位置等;如果没有找到匹配,则返回None
  • match函数:如果在字符串开头匹配成功,返回一个Match对象;否则返回None

示例代码

  1. search函数示例
import re

text = "hello world, 123"
pattern = r'\d+'
match_obj = re.search(pattern, text)
if match_obj:
    print(f"匹配内容: {match_obj.group()}")
    print(f"匹配起始位置: {match_obj.start()}")
    print(f"匹配结束位置: {match_obj.end()}")
else:
    print("未找到匹配内容")
  1. match函数示例
import re

text = "hello world, 123"
pattern = r'hello'
match_obj = re.match(pattern, text)
if match_obj:
    print(f"匹配内容: {match_obj.group()}")
    print(f"匹配起始位置: {match_obj.start()}")
    print(f"匹配结束位置: {match_obj.end()}")
else:
    print("未找到匹配内容")

上述match函数示例中,如果将pattern改为r'world',由于world不在字符串开头,将返回None。而search函数只要字符串内存在world就能匹配到。