Python面试宝典7 | 正则表达式的match()与search(),精准匹配与全局搜索

今天,我们来聊聊Python正则表达式中两个常用的方法:match()search()。它们都用于在字符串中查找匹配的模式,但有着重要的区别。

理论篇:匹配的起始位置

match()search()最主要的区别在于它们匹配的起始位置:

  • match() 尝试从字符串的起始位置 匹配模式。如果匹配成功,则返回一个匹配对象;否则,返回None。也就是说,如果模式不是出现在字符串的开头,match()就无法匹配。
  • search() 在整个字符串中搜索第一个匹配的模式。如果匹配成功,则返回一个匹配对象;否则,返回None。也就是说,模式可以出现在字符串的任何位置。

代码篇:实例演示差异

让我们通过一些代码示例来清晰地展示它们的区别:

python 复制代码
import re

string = "hello world"

# 使用match()
match_result_1 = re.match("hello", string)
match_result_2 = re.match("world", string)

if match_result_1:
    print(f"match() 匹配成功:{match_result_1.group()}") # 输出 match() 匹配成功:hello
else:
    print("match() 匹配失败")

if match_result_2:
    print(f"match() 匹配成功:{match_result_2.group()}")
else:
    print("match() 匹配失败") # 输出 match() 匹配失败

# 使用search()
search_result_1 = re.search("hello", string)
search_result_2 = re.search("world", string)

if search_result_1:
    print(f"search() 匹配成功:{search_result_1.group()}") # 输出 search() 匹配成功:hello
else:
    print("search() 匹配失败")

if search_result_2:
    print(f"search() 匹配成功:{search_result_2.group()}") # 输出 search() 匹配成功:world
else:
    print("search() 匹配失败")


string2 = "oh my world"
match_result_3 = re.match("world", string2)
search_result_3 = re.search("world", string2)

if match_result_3:
    print(f"match() 匹配成功:{match_result_3.group()}")
else:
    print("match() 匹配失败") # 输出 match() 匹配失败

if search_result_3:
    print(f"search() 匹配成功:{search_result_3.group()}") # 输出 search() 匹配成功:world
else:
    print("search() 匹配失败")

在这个例子中:

  • 使用match()匹配"hello"时,因为"hello"在字符串的开头,所以匹配成功。而匹配"world"时,由于"world"不在开头,所以匹配失败。
  • 使用search()匹配"hello"和"world"时,都能成功匹配,因为它会在整个字符串中搜索。
  • 使用match()匹配"oh my world"中的"world"时,由于"world"不在开头,所以匹配失败。而使用search()则匹配成功。

返回值:匹配对象

无论是match()还是search(),如果匹配成功,都会返回一个匹配对象(Match Object)。这个对象包含了一些有用的方法和属性,例如:

  • group():返回匹配的字符串。
  • start():返回匹配的起始位置。
  • end():返回匹配的结束位置。
  • span():返回一个包含匹配的起始和结束位置的元组。

如果没有匹配成功,则返回None

python 复制代码
import re

string = "hello world"
match_result = re.match("hello", string)

if match_result:
    print(f"匹配的字符串:{match_result.group()}") # 输出 匹配的字符串:hello
    print(f"起始位置:{match_result.start()}") # 输出 起始位置:0
    print(f"结束位置:{match_result.end()}") # 输出 结束位置:5
    print(f"起始和结束位置:{match_result.span()}") # 输出 起始和结束位置:(0, 5)

使用场景

  • match() 适用于需要严格匹配字符串开头的情况,例如验证字符串是否以某个特定的前缀开头。
  • search() 适用于需要在字符串中查找某个模式的任何位置的情况,例如在一段文本中查找特定的关键词。

总结篇:精准定位,灵活搜索

match()search()是Python正则表达式中两个重要的匹配方法。理解它们的区别,可以帮助我们更精准地进行字符串匹配和处理。记住:

  • match()从字符串的开头匹配。
  • search()在整个字符串中搜索。

如果觉得不错,随手点个赞吧,如果想第一时间收到推送,也可以关注下我~谢谢你看我的文章,我们,下次再见。

相关推荐
阿尔的代码屋3 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者20 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者20 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django