Python笔记之正则表达式模块`re`模块中的`re.search`与`re.match`的区别

Python笔记之正则表达式模块re模块中的re.searchre.match的区别

在Python的re模块中,re.searchre.match都是用于匹配正则表达式的函数,但它们有一些重要的区别:

  • re.search(pattern, string): 在整个字符串中搜索模式,返回第一个匹配项。如果找到匹配项,则返回一个匹配对象;否则,返回None
  • re.match(pattern, string): 从字符串的起始位置开始匹配模式。如果字符串的开始位置匹配模式,则返回一个匹配对象;否则,返回None

以下是一些详细的比较和示例:

re.search

re.search在整个字符串中搜索第一个匹配项,而不局限在字符串的开始位置。

import re

pattern = r"\d+"
string = "abc123def"

match = re.search(pattern, string)
if match:
    print(f"Found a match: {match.group()}")
else:
    print("No match found")

输出:

Found a match: 123

re.match

re.match仅在字符串的起始位置进行匹配,如果起始位置不匹配,则返回None

import re

pattern = r"\d+"
string = "abc123def"

match = re.match(pattern, string)
if match:
    print(f"Found a match: {match.group()}")
else:
    print("No match found")

输出:

No match found

区别总结

  • re.search:在整个字符串中查找模式,只要字符串中包含匹配项即可。
  • re.match:必须在字符串的起始位置匹配模式,如果起始位置不匹配则返回None

示例对比

以下示例演示了二者的区别:

import re

pattern = r"\d+"
string1 = "123abc"
string2 = "abc123"

# 使用 re.search
search_match1 = re.search(pattern, string1)
search_match2 = re.search(pattern, string2)

# 使用 re.match
match_match1 = re.match(pattern, string1)
match_match2 = re.match(pattern, string2)

print("re.search results:")
print(f"Search in '{string1}':", search_match1.group() if search_match1 else "No match")
print(f"Search in '{string2}':", search_match2.group() if search_match2 else "No match")

print("\nre.match results:")
print(f"Match in '{string1}':", match_match1.group() if match_match1 else "No match")
print(f"Match in '{string2}':", match_match2.group() if match_match2 else "No match")

输出:

re.search results:
Search in '123abc': 123
Search in 'abc123': 123

re.match results:
Match in '123abc': 123
Match in 'abc123': No match

相关推荐

  1. pythonre库 ,表达式模块

    2024-07-22 15:24:02       28 阅读
  2. 表达式pythonre模块使用以及一些习题

    2024-07-22 15:24:02       29 阅读
  3. Python 表达式模块re 模块

    2024-07-22 15:24:02       64 阅读
  4. shell表达式---RE

    2024-07-22 15:24:02       54 阅读
  5. 3.01【python表达式以及re模块

    2024-07-22 15:24:02       54 阅读
  6. Python--表达式re模块基础匹配方法

    2024-07-22 15:24:02       16 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 15:24:02       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 15:24:02       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 15:24:02       45 阅读
  4. Python语言-面向对象

    2024-07-22 15:24:02       55 阅读

热门阅读

  1. 英语(二)-汇总

    2024-07-22 15:24:02       18 阅读
  2. 哪些系统需要进行等级保护

    2024-07-22 15:24:02       19 阅读
  3. oops使用笔记

    2024-07-22 15:24:02       15 阅读
  4. CDN绕过

    2024-07-22 15:24:02       17 阅读
  5. C#中的Action

    2024-07-22 15:24:02       17 阅读
  6. CPU工作原理

    2024-07-22 15:24:02       20 阅读
  7. 以线程完成并发的UDP服务端

    2024-07-22 15:24:02       12 阅读
  8. 自动以当前域用户身份登录

    2024-07-22 15:24:02       16 阅读
  9. Vue3如何实现响应式

    2024-07-22 15:24:02       19 阅读