软件测试|深入理解Python中的re.search()和re.findall()区别

前言

在Python中,正则表达式是一种强大的工具,用于在文本中查找、匹配和处理模式。re 模块提供了许多函数来处理正则表达式,其中 re.search()re.findall() 是常用的两个函数,用于在字符串中查找匹配的模式。本文将深入介绍这两个函数的用法,以及详细的使用示例。

re.search() 函数

re.search() 函数用于在字符串中查找匹配的第一个子串,并返回一个匹配对象。如果找到了匹配,可以通过匹配对象的方法和属性来获取相关信息。

python 复制代码
import re

pattern = r'apple'
text = "I have an apple and a banana."

# 在文本中查找第一个匹配的子串
match = re.search(pattern, text)

if match:
    print("Found:", match.group())  # 获取匹配的子串
    print("Start:", match.start())  # 获取匹配的起始位置
    print("End:", match.end())      # 获取匹配的结束位置
else:
    print("No match found.")

re.findall() 函数

re.findall() 函数用于在字符串中查找所有匹配的子串,并返回一个包含所有匹配结果的列表。

python 复制代码
import re

pattern = r'\d+'  # 匹配一个或多个数字
text = "I have 3 apples and 5 bananas. Total 8 fruits."

# 查找所有匹配的子串
matches = re.findall(pattern, text)

if matches:
    print("Matches:", matches)  # 获取所有匹配的子串列表
else:
    print("No matches found.")

使用示例

  1. 使用 re.search() 查找日期
python 复制代码
import re

pattern = r'\d{2}-\d{2}-\d{4}'  # 匹配日期格式:dd-mm-yyyy
text = "Today's date is 31-08-2023."

match = re.search(pattern, text)

if match:
    print("Date found:", match.group())
else:
    print("No date found.")
  1. 使用 re.findall() 查找所有链接
python 复制代码
import re

pattern = r'https?://\S+'  # 匹配HTTP或HTTPS链接
text = "Here are some links: https://www.example.com and http://google.com"

links = re.findall(pattern, text)

if links:
    print("Links found:", links)
else:
    print("No links found.")
  1. 使用 re.findall() 查找电子邮件地址
python 复制代码
import re

pattern = r'\w+@\w+\.\w+'  # 匹配基本电子邮件地址
text = "Contact us at support@example.com or info@company.net"

emails = re.findall(pattern, text)

if emails:
    print("Email addresses found:", emails)
else:
    print("No email addresses found.")

总结

re.search() 用于查找第一个匹配的子串,而 re.findall() 则用于查找所有匹配的子串。通过在正则表达式模式中定义适当的规则,使得我们可以有效地在文本中查找并处理各种模式。这两个函数是处理文本匹配和搜索的重要工具,在文本处理和数据提取中非常有用。

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

相关推荐
2603_965148117 小时前
如何解析JSON数据?API返回的商品信息处理教程
开发语言·数据库·python·自动化·json·api
fqq37 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
jufeng13078 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 8 篇】
python·ai agent·配置系统
circuitsosk9 小时前
跨境电商智能化实战:AI如何赋能客服自动回复、广告智能投放与供应链预测
大数据·人工智能·python·langchain·智能客服
2601_956319889 小时前
2026年零基础学量化:从看懂示例到写清条件和动作
人工智能·python
Thecozzy9 小时前
大厂 AI Coding 面试大招
人工智能·面试·职场和发展
知无不研9 小时前
lambda表达式的使用(3)
开发语言·c++·lambda
过期的秋刀鱼!10 小时前
LangChain-D1-模型的工作流程
人工智能·python·langchain
萤火工厂目视化设计10 小时前
智能制造与企业文化目视化浪潮下:中小工厂的机遇与挑战
python·制造
cfm_291410 小时前
SpringAI + Ollama 本地大模型
java·开发语言·人工智能·语言模型