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()在整个字符串中搜索。

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

相关推荐
万粉变现经纪人8 小时前
如何解决 pip install 安装报错 ModuleNotFoundError: No module named ‘tokenizers’ 问题
python·selenium·测试工具·scrapy·beautifulsoup·fastapi·pip
编程武士9 小时前
从50ms到30ms:YOLOv10部署中图像预处理的性能优化实践
人工智能·python·yolo·性能优化
我的xiaodoujiao10 小时前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
傻啦嘿哟12 小时前
Python SQLite模块:轻量级数据库的实战指南
数据库·python·sqlite
Q_Q51100828512 小时前
python+django/flask+uniapp基于微信小程序的瑜伽体验课预约系统
spring boot·python·django·flask·uni-app·node.js·php
XueminXu12 小时前
Python读取MongoDB的JSON字典和列表对象转为字符串
python·mongodb·json·pymongo·mongoclient·isinstance·json.dumps
techdashen13 小时前
12分钟讲解Python核心理念
开发语言·python
jie*13 小时前
小杰机器学习(nine)——支持向量机
人工智能·python·机器学习·支持向量机·回归·聚类·sklearn
闭着眼睛学算法13 小时前
【华为OD机考正在更新】2025年双机位A卷真题【完全原创题解 | 详细考点分类 | 不断更新题目 | 六种主流语言Py+Java+Cpp+C+Js+Go】
java·c语言·javascript·c++·python·算法·华为od
郝学胜-神的一滴13 小时前
谨慎地迭代函数所收到的参数 (Effective Python 第31条)
开发语言·python·程序人生·软件工程