商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > Python中如何使用正则表达式进行字符串匹配和替换详解

Python中如何使用正则表达式进行字符串匹配和替换详解

  发布于2026-07-05 阅读(0)

扫一扫,手机访问

在Python里,正则表达式就像一把瑞士军刀——专门用来处理字符串的搜索、替换、分割这些琐事。而re模块正是这把刀的工具箱,里面装满了各种好用的函数。下面我们就从最基础的导入开始,一步步看看怎么用正则搞定匹配和替换。

Python中如何使用正则表达式进行字符串匹配和替换详解

1. 导入re模块

动手之前,先得把re模块请出来。它就像工具箱的钥匙,没有它,后面的操作都无从谈起。

import re

2. 使用re.sub()函数进行字符串替换

re.sub()是替换的主力军,它能把字符串里所有匹配正则表达式的部分统统换成你指定的内容。语法长这样:

re.sub(pattern, repl, string, count=0, flags=0)
  • pattern:要匹配的正则模式。

  • repl:替换成什么?可以是字符串,也可以是一个函数(后面会看到它的妙用)。

  • string:原始字符串。

  • count:最多替换几次,默认0代表全部替换。

  • flags:匹配模式,比如忽略大小写。

示例1:

把"ja va script"改成"ja vascript"(注意这里加了单词边界,避免误伤"ja vascripter"之类的词)。

import re

text = "ja va script is awesome."
pattern = r"\bja va script\b"
repl = "ja vascript"
new_text = re.sub(pattern, repl, text)
print(new_text)  # 输出: ja vascript is awesome.

示例2:

把字符串中的所有四位数字替换成"****"。

import re

text = "1234 hello 5678 world"
pattern = r"\b\d{4}\b"
repl = "****"
new_text = re.sub(pattern, repl, text)
print(f'Original string: {text}')
print(f'Replaced string: {new_text}')
# 输出:
# Original string: 1234 hello 5678 world
# Replaced string: **** hello **** world

3. 使用re.search()函数进行字符串匹配

re.search()不会从头开始,而是在整个字符串里搜索第一个匹配的位置。语法:

re.search(pattern, string, flags=0)
  • pattern:正则模式。

  • string:原始字符串。

  • flags:可选匹配模式。

示例:

检查字符串里有没有"World"。

import re

text = "Hello World"
pattern = r"World"
match = re.search(pattern, text)
if match:
    print("匹配成功")
    print(match.group())  # 输出: World
else:
    print("匹配失败")

4. 使用re.match()函数进行字符串匹配

re.match()search的区别在于——它只从字符串开头开始匹配,开头对不上就直接返回None

re.match(pattern, string, flags=0)
  • pattern:正则模式。

  • string:原始字符串。

  • flags:可选匹配模式。

示例:

看看字符串是不是以"Hello"开头。

import re

text = "Hello World"
pattern = r"Hello"
match = re.match(pattern, text)
if match:
    print("匹配成功")
    print(match.group())  # 输出: Hello
else:
    print("匹配失败")

5. 使用正则表达式进行复杂的字符串替换

有时候替换逻辑不是固定的——比如想把所有数字都翻倍,这时候就需要一个替换函数登场了。

示例:

把字符串里的每个数字都替换成它自己的两倍。

import re

text = "The numbers are 123 and 456."
pattern = r"\d+"

def double(match):
    num = int(match.group())
    return str(num * 2)

new_text = re.sub(pattern, double, text)
print(new_text)  # 输出: The numbers are 246 and 912.

6. 使用正则表达式进行多模式替换

如果同时要替换好几个单词,用字典配合循环就能优雅搞定。注意要对字典的键先做转义,防止特殊字符捣乱。

示例:

把"apple"换成"orange","banana"换成"grape"。

import re

text = "apple banana cherry"
rep = {"apple": "orange", "banana": "grape"}

# 把字典的键转义一下
rep = dict((re.escape(k), v) for k, v in rep.items())

# 用"|"把多个模式拼成一个大的正则
pattern = re.compile("|".join(rep.keys()))

# 替换时取字典里对应的值
new_text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
print(new_text)  # 输出: orange grape cherry

7. 使用正则表达式进行贪婪和非贪婪匹配

默认情况下,*+这些量词是贪婪的——能多匹配就多匹配。要想让它们“知足常乐”,就在后面加个?

示例:

从HTML标签里提取内容,贪婪和非贪婪的结果完全不同。

import re

text = "Example Content"

# 贪婪匹配 (.会跨过中间的所有字符)
pattern_greedy = r"(.*)"
match_greedy = re.search(pattern_greedy, text)
if match_greedy:
    print("贪婪匹配结果:", match_greedy.group(1))  # 输出: Example Content

# 非贪婪匹配 (能停就停)
pattern_non_greedy = r"(.*?)"
match_non_greedy = re.search(pattern_non_greedy, text)
if match_non_greedy:
    print("非贪婪匹配结果:", match_non_greedy.group(1))  # 输出: Example

8. 使用正则表达式进行忽略大小写匹配

设置flags=re.IGNORECASE(或者缩写re.I),正则就不分大小写了。

示例:

用"hello"去匹配"Hello World"。

import re

text = "Hello World"
pattern = r"hello"
match = re.search(pattern, text, re.IGNORECASE)
if match:
    print("匹配成功")
    print(match.group())  # 输出: Hello
else:
    print("匹配失败")

总结

从简单的替换到复杂的动态处理,Python的re模块确实能把字符串操作变得灵活又高效。这些例子只是冰山一角——当你真正熟悉了正则,处理日志、清洗数据、提取信息都会顺手很多。关键是理解每个参数的用意,多动手写几个例子,那些看似复杂的模式很快就变成肌肉记忆了。

本文转载于:https://www.jb51.net/python/366533aq0.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注