一篇文章精通正则表达式与re模块(含案例)

 更新时间:2026年07月08日 10:49:41   作者:榴莲终结者  
正则表达式就是为了利用特殊符号,快速实现字符串的匹配,这篇文章主要介绍了正则表达式与re模块的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

一、正则简介

正则表达式(Regular Expression,常简称 “正则” 或 regex),也叫正规表示法,本质上是一套用来描述文本排列规则的表达式。它可以精准定义字符串的匹配模式,是处理复杂文本信息的强大工具。

正则表达式并非 Python 专属,它是一套独立于编程语言的文本处理标准,拥有自身独特的语法规则和独立的正则引擎。当我们用正则语法编写好匹配规则(模式)后,引擎不仅能执行模糊文本查找,还能完成模糊分割、内容替换等复杂操作,让开发者可以灵活高效地处理各类文本信息。多数编程语言都会提供操作正则引擎的接口,比如 Python 就内置了 re 模块来实现正则功能。

尽管在简单文本处理场景中,正则的效率略逊于编程语言自带的字符串操作,但它的功能覆盖面和处理复杂场景的能力,是普通字符串操作无法比拟的。

正则表达式最早起源于 Perl 语言,后续包括 Java、PHP、Go、JavaScript、SQL 在内的大多数编程语言,在实现正则功能时都沿用了 Perl 的核心语法。这意味着你在 Python 中学到的正则知识,几乎可以无缝迁移到其他语言中,具备极高的通用性。

总的来说,无论是哪种编程语言,对字符串或文本的核心操作都离不开分割、匹配、查找、替换这四类场景,而正则正是为高效解决这些问题而生的工具。

二、元字符

正则表达式的核心威力,来自于它定义的一系列 “元字符”。这些特殊字符不再代表字面含义,而是被赋予了匹配规则的功能,是我们构建复杂匹配模式的基础。

1、通配符

通配符是正则里最基础的元字符,其中最具代表性的就是英文句号 .

匹配规则:它可以匹配除了换行符(\n)之外的任意单个字符。

import re
# . 匹配一个任意字符(除换行符)
s = "apple a%e a9e agree age amazee animate advertise a\ne"
result1 = re.findall("a.e", s)
print(result1)  # ['a%e', 'a9e', 'age', 'aze', 'ate']
result2 = re.findall("a..e", s)
print(result2)  # ['agre', 'azee', 'adve']
result3 = re.findall("a...e", s)
print(result3)  # ['apple', 'agree', 'amaze']
result4 = re.findall("a....e", s)
print(result4)  # ['amazee']
result5 = re.findall("a.....e", s)
print(result5)  # ['a%e a9e', 'animate']
result6 = re.findall("a......e", s)
print(result6)  # ['a9e agre', 'ate adve']

2、字符集

当我们希望匹配某一类特定字符,而不是任意字符时,就需要用到字符集(Character Set)。它用方括号 [] 来定义。

匹配规则:方括号中的任意一个字符都会被匹配,且字符集只匹配单个位置。

import re
# [] 字符集 匹配字符集中的任意一个字符
s = "apple a%e a9e agree age amazee aYe animate a1e a#e advertise a\ne"
result1 = re.findall("a[g]e", s)
print(result1)  # ['age']
result2 = re.findall("a[g9]e", s)
print(result2)  # ['a9e', 'age']
result3 = re.findall("a[g9%]e", s)
print(result3)  # ['a%e', 'a9e', 'age']
result4 = re.findall("a[0123456789]e", s)
print(result4)  # ['a9e', 'a1e']
# [0-9] 等价于 [0123456789]
result5 = re.findall("a[0-9]e", s)
print(result5)  # ['a9e', 'a1e']
result6 = re.findall("a[a-z]e", s)
print(result6)  # ['age', 'aze', 'ate']
# [a-zA-Z] 等价于 所有大小写英文字母
result6 = re.findall("a[a-zA-Z]e", s)
print(result6)  # ['age', 'aze', 'aYe', 'ate']
# [^字符集] 匹配除了字符集中的任意一个字符
result7 = re.findall("a[^0-9]e", s)
print(result7)  # ['a%e', 'age', 'aze', 'aYe', 'ate', 'a#e', 'a\ne']

进阶核心用法

  1. 范围表示:通过连字符 - 表示连续字符范围,简化多字符书写,[a-z] 匹配任意小写字母、[0-9] 匹配任意数字、[A-Za-z0-9_] 匹配任意字母 / 数字 / 下划线。

  2. 取反操作:在字符集开头加脱字符 ^,表示匹配除括号内字符外的任意单个字符[^0-9] 匹配任意非数字字符。

3、重复元字符

在实际文本处理中,我们常需要匹配连续出现多次的字符 / 子模式(比如匹配 1 个或多个数字、0 个或多个字母),此时通配符和字符集的单字符匹配能力已无法满足需求,重复元字符(量词元字符) 应运而生 —— 它可以指定某个字符 / 子模式的重复匹配次数,是实现多字符批量匹配的核心元字符,让正则匹配规则从 “单字符” 拓展到 “多字符”。

重复元字符均为后缀式使用,即紧跟在需要被指定重复次数的目标字符 / 子模式后,仅对其紧邻的前一个匹配单元生效。

(1):{}

{n,m}:数量范围贪婪符,指定左边原子的数量范围,有{n},{n,},{m},{n,m}四种写法,其中n与m必须是非负整数

import re

s = "aeeee apple a%e a9e agree age amazee aYe animate a1e a#e advertise a\ne wjh"
result1 = re.findall("a...e", s)
print(result1)  # ['aeeee', 'apple', 'agree', 'amaze']
# .{3} 表示任意字符出现3次 即.重复三次
result2 = re.findall("a.{3}e", s)
print(result2)  # ['aeeee', 'apple', 'agree', 'amaze']
# .{1,3} 表示任意字符出现1到3次,贪婪匹配,按着最大的匹配数去匹配
result3 = re.findall("a.{1,3}e", s)
print(result3)  # ['aeeee', 'apple', 'a%e', 'a9e', 'agree', 'age', 'amaze', 'aYe', 'ate', 'a1e', 'a#e', 'adve']
# 如何取消贪婪匹配 加上?,取消贪婪匹配,按着最小的匹配数去匹配
result4 = re.findall("a.{1,3}?e", s)
print(result4)  # ['aee', 'apple', 'a%e', 'a9e', 'agre', 'age', 'amaze', 'aYe', 'ate', 'a1e', 'a#e', 'adve']
"""
可以看到'aeeee'在贪婪匹配.{1,3}下 匹配到了'aeeee',取消贪婪匹配.{1,3}?下 匹配到了'aee'
"""
# .{4,} 表示任意字符出现4次或多次 贪婪
result5 = re.findall("a.{4,}e", s)
print(result5)  # ['aeeee apple a%e a9e agree age amazee aYe animate a1e a#e advertise']
# .{4,}? 表示任意字符出现4次或多次 取消贪婪
result6 = re.findall("a.{4,}?e", s)
print(result6)  # ['aeeee apple', 'a%e a9e', 'agree age', 'amazee', 'aYe animate', 'a1e a#e', 'advertise']
# 和字符集配合 寻找单词 [a-z]{1,4} 表示任意小写字母出现1到4次
result6 = re.findall("a[a-z]{1,4}e", s)
print(result6)  # ['aeeee', 'apple', 'agree', 'age', 'amazee', 'ate', 'adve']

(2):*

*指定左边原子出现0次或多次,等同{0,}

import re

s = "aeeee apple a%e a9e agree age amazee aYe animate a1e a#e advertise a\ne wjh"
result1 = re.findall("a.{0,}e", s)
print(result1)  # ['aeeee apple a%e a9e agree age amazee aYe animate a1e a#e advertise']
# .{0,} 等同于 a.*e
result2 = re.findall("a.*e", s)
print(result2)  # ['aeeee apple a%e a9e agree age amazee aYe animate a1e a#e advertise']
# 贪婪模式用得少,我们一般用非贪婪模式
result3 = re.findall("a.*?e", s)
print(result3)  # ['ae', 'apple', 'a%e', 'a9e', 'agre', 'age', 'amaze', 'aYe', 'animate', 'a1e', 'a#e', 'adve']

(3):+

+指定左边原子出现1次或多次,等同{1,}

import re

s = "aeeee apple a%e a9e agree age amazee aYe animate a1e a#e advertise a\ne wjh"
result1 = re.findall("a.{1,}e", s)
print(result1)  # ['aeeee apple a%e a9e agree age amazee aYe animate a1e a#e advertise']
# .{1,} 等同于 a.+e
result2 = re.findall("a.+e", s)
print(result2)  # ['aeeee apple a%e a9e agree age amazee aYe animate a1e a#e advertise']
# 贪婪模式用得少,我们一般用非贪婪模式
result3 = re.findall("a.+?e", s)
print(result3)  # ['aee', 'apple', 'a%e', 'a9e', 'agre', 'age', 'amaze', 'aYe', 'animate', 'a1e', 'a#e', 'adve']

(4):?

?指定左边原子出现1次或多次,等同{0,1}

import re

s = "https://www.baidu.com/,http://www.jd.com/,http://www.taobao.com/,https://www.zhihu.com/"
result1 = re.findall("https://www.[a-z]*?.com/", s)
print(result1)  # ['https://www.baidu.com/', 'https://www.zhihu.com/']
# 只能拿https的
# 我们用上 ?
result2 = re.findall("https?://www.[a-z]*?.com/", s)
print(result2)  # ['https://www.baidu.com/', 'http://www.jd.com/', 'http://www.taobao.com/', 'https://www.zhihu.com/']

(5):总结

常用核心重复元字符

重复元字符 核心匹配规则简单示例示例匹配结果
{n}匹配前一个单元恰好 n 次(n 为非负整数)a{3}b仅匹配aaab
{n,}匹配前一个单元至少 n 次(n 次及以上)a{2,}baabaaabaaaab(不匹配abb
{n,m}匹配前一个单元n 到 m 次(包含 n 和 m,n≤m)a{1,3}babaabaaab(不匹配baaaab
*匹配前一个单元0 次或任意多次(0 次即允许不出现)a*bbabaabaaab
+匹配前一个单元1 次或任意多次(至少出现 1 次)a+babaabaaab(不匹配b
?匹配前一个单元0 次或 1 次(最多出现 1 次,可选)a?bbab(不匹配aab

贪婪匹配 vs 非贪婪匹配

重复元字符默认采用贪婪匹配策略,即尽可能匹配最多的符合规则的字符;若在重复元字符后追加一个?,则会切换为非贪婪匹配,即尽可能匹配最少的符合规则的字符。

匹配模式语法形式核心策略示例正则待匹配字符串匹配结果
贪婪匹配a{1,3}取最大允许次数匹配a{1,3}aaaaaaaa
非贪婪匹配a{1,3}? 取最小允许次数匹配a{1,3}?a

4、^和$

在正则匹配中,我们常会遇到精准匹配整行内容、限定字符出现位置的需求(比如匹配纯数字的手机号、纯字母的用户名,而非字符串中夹杂的数字 / 字母片段),此时就需要用到边界匹配元字符^$是最核心的一对行边界匹配元字符,专门用于限定字符串 / 行的开头和结尾,让匹配规则从 “模糊查找片段” 升级为 “精准匹配整体”。

^$本身不匹配任何具体字符,仅用于标记位置,属于 “零宽匹配” 元字符(匹配结果不占字符长度),二者常配合使用实现整行精准匹配,也可单独使用限定单边位置。

import re

# ^ 表示匹配字符串的开头
s1 = '123abc'
s2 = 'abc123'
print(re.findall(r'^[0-9]', s1))  # ['1']
print(re.findall(r'^[0-9]', s2))  # []

# $ 表示匹配字符串的结尾
s3 = '123a'
s4 = 'test5'
print(re.findall(r'[a-zA-Z]$', s3))  # ['a']
print(re.findall(r'[a-zA-Z]$', s4))  # []

^$组合使用是实际开发中最常用的方式,核心解决 **“纯内容匹配”** 问题,避免匹配到夹杂目标内容的无效字符串,这是正则实现精准校验的基础,典型实用场景如下:

import re

# 校验纯 11 位手机号(仅数字校验,简易版)
s1 = '13800138000'
s2 = '13800138000 '
print(re.findall(r'^[0-9]{11}$', s1))  # ['13800138000']
print(re.findall(r'^[0-9]{11}$', s2))  # []
# 校验仅由字母 / 数字组成的 3-8 位用户名
s3 = 'abc123'
s4 = 'abc12_3'
print(re.findall(r'^[a-zA-Z0-9]{3,8}$', s3))  # ['abc123']
print(re.findall(r'^[a-zA-Z0-9]{3,8}$', s4))  # []

Python re 模块的行匹配扩展:re.MULTILINE 标志

默认情况下,^仅匹配整个字符串的开头$仅匹配整个字符串的结尾,即使字符串包含多个换行符(\n),也不会将每行单独作为匹配单元。

若需要对多行字符串实现 “按行匹配”(即^匹配每行开头、$匹配每行结尾),可在 re 模块函数中指定 **re.MULTILINE(简写re.M)** 标志,这一特性在处理日志、文本文件等多行内容时尤为实用。

import re

# 多行待匹配字符串(含3行,每行内容不同)
multi_text = "123abc\n456def\n789ghi"

# 无re.M标志:默认匹配整个字符串开头,仅能找到1个结果
default_result = re.findall(r"^[0-9]{3}", multi_text)
print("默认匹配结果:", default_result)  # ['123']

# 加re.M标志:按行匹配,每行开头的3位数字都能被匹配
multi_result = re.findall(r"^[0-9]{3}", multi_text, flags=re.M)
print("按行匹配结果:", multi_result)  # ['123', '456', '789']

# 按行匹配以字母结尾的行(整行匹配)
line_end_result = re.findall(r"[a-z]{3}$", multi_text, flags=re.M)
print("按行匹配结尾字母结果:", line_end_result)  # ['abc', 'def', 'ghi']

注意:与字符集内 ^ 的区别:字符集[]内的^取反操作(如[^0-9]匹配非数字),而单独使用的^开头边界匹配,二者语法位置不同,含义完全无关,切勿混淆;

5、转义符 \

正则中的转义符和Python字符串的转义符相似,两个功能

(1):为普通字符赋予特殊含义

元字符说明
\d匹配数字,等于[0-9]
\D匹配非数字,等于[^0-9]或[^\d]
\w匹配单词字符(字母、数字、下划线),等于[0-9a-zA-Z_]
\W匹配非单词字符,等于[^0-9a-zA-Z_]或[^\w]
\s匹配空白字符(空格、制表符等)
\S匹配非空白字符
\n匹配换行符
\t匹配制表符,tab键
\s匹配一个任何空白字符原子,包括空格、制表符、换页符等等。
\S匹配一个任何非空白字符原子。
\b匹配一个单词边界原子,也就是指单词和空格间的位置。
\B匹配一个非单词边界原子,等价于[^\b]
import re

s1 = "wjh\nage 24 shengao 185 gender m price 9999 birthday! 0109"
# \d	匹配数字,等于[0-9]
print(re.findall(r"\d", s1))  # ['2', '4', '1', '8', '5', '9', '9', '9', '9', '0', '1', '0', '9']
print(re.findall(r"\d+", s1))  # ['24', '185', '9999', '0109']
# \D	匹配非数字,等于[^0-9]或[^\d]
print(re.findall(r"\D+", s1))  # ['wjh\nage ', ' shengao ', ' gender men price ', ' birthday! ']
# \w	匹配单词字符(字母、数字、下划线),等于[0-9a-zA-Z_]
print(re.findall(r"\w+", s1))  # ['wjh', 'age', '24', 'shengao', '185', 'gender', 'men', 'price', '9999', 'birthday', '0109']
# \W	匹配非单词字符,等于[^0-9a-zA-Z_]或[^\w]
print(re.findall(r"\W+", s1))  # ['\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '! ']
# \s	匹配空白字符(空格、制表符等)
print(re.findall(r"\s", s1))  # ['\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
# \S	匹配非空白字符
print(re.findall(r"\S+", s1))  # ['wjh', 'age', '24', 'shengao', '185', 'gender', 'men', 'price', '9999', 'birthday!', '0109']
s2 = "cat cat2 cat! ccatc"
# \b	匹配一个单词边界原子,也就是指单词和空格间的位置。
print(re.findall(r"\bcat\b", s2))  # ['cat', 'cat'] 只有cat和cat!能匹配
# \B	匹配一个非单词边界原子,等价于[^\b]
print(re.findall(r"\Bcat\B", s2))  # ['cat']只有ccatc能匹配

(2):匹配元字符本身(消除特殊含义)

import re

s = "https://wwwwbaidu.com/,http://www.jd.com/,http://www.taobao.com/,https://www.zhihu.com/"
result1 = re.findall("https?://www.[a-z]*?.com/", s)
print(result1)  # ['https://wwwwbaidu.com/', 'http://www.jd.com/', 'http://www.taobao.com/', 'https://www.zhihu.com/']
"""
我们不想匹配https://wwwwbaidu.com/,因为www后面有两个w,所以我们需要使用转义符
"""
result2 = re.findall(r"https?://www\.[a-z]*?.com/", s)
print(result2)  # ['http://www.jd.com/', 'http://www.taobao.com/', 'https://www.zhihu.com/']

6、()分组与优先提取

在正则的实际使用中,我们会发现仅靠单字符 / 单一匹配单元的组合,无法满足多字符整体重复、多规则分支匹配、匹配结果精准提取的需求(比如匹配ab重复 3 次、匹配手机号/邮箱二选一、从匹配结果中单独提取数字部分)。

此时分组元字符() 成为核心解决方案 —— 它能将括号内的任意字符 / 子模式包裹为一个独立的匹配单元(分组),让重复、边界等元字符对整个分组生效;同时分组还支持优先提取匹配结果,能从整体匹配内容中精准拆分出我们需要的子内容,是正则从 “基础匹配” 升级为 “复杂场景匹配 + 结果解析” 的关键元字符。

(1):构建独立匹配单元

import re

s = 'ab abb abbb abab'
result1 = re.findall('ab{1,3}', s)  # {1,3}只作用于b
print(result1)  # ['ab', 'abb', 'abbb', 'ab', 'ab']
result2 = re.findall('(ab){1,3}', s)  # {1,3}作用于ab
print(result2)

(2):优先提取匹配结果

import re

text = "小明28岁 小红25岁 小李30岁"

result = re.findall("\w+?(\d+)岁", text)
print("提取的年龄:", result)  # 输出:['28', '25', '30']

(3):非捕获分组(?:)

import re
text = "abab ababb aabb ababab"

# 1. 普通捕获分组 ():仅分组,也会捕获
# (ab){2} 把ab设为整体重复2次,但()会让findall优先返回分组内的ab
capture_res = re.findall(r"(ab){2}", text)
print("普通捕获分组结果:", capture_res)  # 输出:['ab', 'ab'](只返回分组内的ab,而非完整的abab)

# 2. 非捕获分组 (?:):仅分组,不捕获
# (?:ab){2} 仅把ab设为整体重复2次,不捕获,findall返回完整匹配结果
non_capture_res = re.findall(r"(?:ab){2}", text)
print("非捕获分组结果:", non_capture_res)  # 输出:['abab', 'abab'](直接返回完整的abab,符合需求)

7、分支元字符|

在正则匹配的实际场景中,我们常遇到多规则任选其一匹配的需求,比如匹配手机号或固定电话、匹配邮箱或用户名、匹配中文或英文名称,此时单一的匹配规则已无法满足需求,分支元字符| 应运而生。

import re

s1 = "apple banana cherry orange"
print(re.findall(r"apple|banana", s1))  # ['apple', 'banana']

s2 = "联系电话:13800138000 办公电话:010-12345678 无效号码:123456"
# 正则:(\d{11})|(\d{3}-\d{7,8})  两个分组分支,分别匹配手机号、固定电话
result1 = re.findall(r"(\d{11})|(\d{3}-\d{7,8})", s2)
# 处理结果:过滤元组中的空值,提取有效匹配
final_result = [item for tup in result1 for item in tup if item]
print(final_result)  # ['13800138000', '010-12345678']

s3 = "python pycharm pygame pyjava python123"
# 正则:py(thon|charm|game)  前缀py固定,分组内分支匹配后缀可选规则
result2 = re.findall(r"py(thon|charm|game)", s3)
print(result2)  # ['thon', 'charm', 'game', 'thon'](仅提取分组内分支内容)
# 若需提取完整单词,将整个规则设为非捕获分组或整体匹配
result3 = re.findall(r"py(?:thon|charm|game)", s3)
print(result3)  # ['python', 'pycharm', 'pygame', 'python']

三、案例

案例一:百度热搜

import re

html = """
<div id="s-hotsearch-wrapper" class="s-isindex-wrap s-hotsearch-wrapper  s-hotsearch-wrapper-login  s-hotsearch-wrapper-new-hot"><div class="s-hotsearch-title"><a class="hot-title" href="https://top.baidu.com/board?platform=pc&amp;sa=pcindex_entry" rel="external nofollow"  target="_blank"><div class="title-text c-font-medium c-color-t" aria-label="百度热搜"><img class="hot-title-icon" src="https://psstatic.cdn.bcebos.com/basics/aichat/hot_search_x3_1747880381000.png" alt=""><i class="c-icon arrow"></i></div></a><a id="hotsearch-refresh-btn" class="hot-refresh c-font-normal c-color-gray2"><i class="c-icon refresh-icon"></i><span class="hot-refresh-text">换一换</span></a></div><ul class="s-hotsearch-content" id="hotsearch-content-wrapper">
<li class="hotsearch-item odd" data-index="0"><a class="title-content  c-link c-font-medium c-line-clamp1" href="https://www.baidu.com/s?wd=%E4%B8%AD%E9%9D%9E%E6%90%BA%E6%89%8B%E5%85%B1%E9%80%90%E5%8F%91%E5%B1%95%E6%8C%AF%E5%85%B4%E6%A2%A6&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: inline-block;"></i><span class="title-content-index c-index-single c-index-single-hot0 c-index-single-hot-new" style="display: none;">0</span><span class="title-content-title">中非携手共逐发展振兴梦</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small"></span></li>
<li class="hotsearch-item even" data-index="5"><a class="title-content c-link c-font-medium c-line-clamp1 tag-width" href="https://www.baidu.com/s?wd=%E4%BD%95%E7%8C%B7%E5%90%9B%E5%BD%93%E9%80%89%E6%96%B0%E8%81%8C&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot5 c-index-single-hot-new" style="display: inline-block;">5</span><span class="title-content-title">何猷君当选新职</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small c-text-new">新</span></li>
<li class="hotsearch-item odd" data-index="1"><a class="title-content c-link c-font-medium c-line-clamp1 tag-width" href="https://www.baidu.com/s?wd=%E4%B8%AB%E4%B8%AB%E5%9B%9E%E5%9B%BD%E4%B8%A4%E5%B9%B4%E5%A4%9A%E5%B7%B2%E5%88%A4%E8%8B%A5%E4%B8%A4%E7%86%8A&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot1 c-index-single-hot-new" style="display: ;">1</span><span class="title-content-title">丫丫回国两年多已判若两熊</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small c-text-hot">热</span></li>
<li class="hotsearch-item even" data-index="6"><a class="title-content c-link c-font-medium c-line-clamp1 tag-width" href="https://www.baidu.com/s?wd=%E8%A7%A3%E6%94%BE%E5%86%9B%E5%86%9B%E6%9C%BA%E9%A3%9E%E8%BF%9B%E8%8F%B2%E5%86%9B%E6%BC%94%E5%88%92%E8%AE%BE%E5%8C%BA&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot6 c-index-single-hot-new" style="display: ;">6</span><span class="title-content-title">解放军军机飞进菲军演划设区</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small c-text-hot">热</span></li>
<li class="hotsearch-item odd" data-index="2"><a class="title-content c-link c-font-medium c-line-clamp1 tag-width" href="https://www.baidu.com/s?wd=%E7%BE%8E%E5%9B%BD%E6%94%BF%E5%BA%9C%E5%8F%88%E2%80%9C%E5%81%9C%E6%91%86%E2%80%9D%E4%BA%86&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot2 c-index-single-hot-new" style="display: ;">2</span><span class="title-content-title">美国政府又“停摆”了</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small c-text-new">新</span></li>
<li class="hotsearch-item even" data-index="7"><a class="title-content  c-link c-font-medium c-line-clamp1" href="https://www.baidu.com/s?wd=%E5%9D%87%E4%BB%B7300%E5%85%83%2F%E5%85%8B%E5%85%A5%E6%89%8B%E7%9A%84%E9%87%91%E6%9D%A1+%E9%98%BF%E5%A7%A8%E5%85%A8%E5%8D%96%E4%BA%86&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot7 c-index-single-hot-new" style="display: ;">7</span><span class="title-content-title">均价300元/克入手的金条 阿姨全卖了</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small"></span></li>
<li class="hotsearch-item odd" data-index="3"><a class="title-content  c-link c-font-medium c-line-clamp1" href="https://www.baidu.com/s?wd=%E5%88%B7%E6%96%B0%E5%A4%9A%E9%A1%B9%E7%BA%AA%E5%BD%95%EF%BC%81%E4%B8%AD%E5%9B%BD%E5%9C%A8%E5%A4%9A%E9%A2%86%E5%9F%9F%E5%AE%9E%E7%8E%B0%E7%AA%81%E7%A0%B4&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot3 c-index-single-hot-new" style="display: ;">3</span><span class="title-content-title">刷新多项纪录!中国在多领域实现突破</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small"></span></li>
<li class="hotsearch-item even" data-index="8"><a class="title-content  c-link c-font-medium c-line-clamp1" href="https://www.baidu.com/s?wd=%E6%97%A9%E7%9D%A1%E6%97%A9%E8%B5%B7%E5%92%8C%E6%99%9A%E7%9D%A1%E6%99%9A%E8%B5%B7%E7%9A%84%E4%BA%BA+%E8%B0%81%E6%9B%B4%E5%81%A5%E5%BA%B7&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot8 c-index-single-hot-new" style="display: ;">8</span><span class="title-content-title">早睡早起和晚睡晚起的人 谁更健康</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small"></span></li>
<li class="hotsearch-item odd" data-index="4"><a class="title-content  c-link c-font-medium c-line-clamp1" href="https://www.baidu.com/s?wd=%E8%88%9F%E5%B1%B1%E5%AE%88%E5%B2%9B%E4%BA%BA%E6%8B%9B2%E7%94%B72%E5%A5%B3%EF%BC%9A2%E4%B8%AA%E6%9C%88%E4%B8%8B1%E6%AC%A1%E5%B2%9B&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot4 c-index-single-hot-new" style="display: inline-block;">4</span><span class="title-content-title">舟山守岛人招2男2女:2个月下1次岛</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small"></span></li>
<li class="hotsearch-item even" data-index="9"><a class="title-content c-link c-font-medium c-line-clamp1 tag-width" href="https://www.baidu.com/s?wd=%E8%8A%B1%E7%94%9F%E8%BF%99%E8%BE%88%E5%AD%90%E6%B2%A1%E6%83%B3%E5%88%B0%E8%BF%98%E8%83%BD%E8%A2%AB%E5%88%87%E4%B8%9D&amp;sa=fyb_n_homepage&amp;rsv_dl=fyb_n_homepage&amp;from=super&amp;cl=3&amp;tn=baidutop10&amp;fr=top1000&amp;rsv_idx=2&amp;hisfilter=1" rel="external nofollow"  target="_blank"><div class="title-content-noindex title-content-noindex-new" style="display: none;"></div><i class="c-icon title-content-top-icon c-color-red c-gap-right-small" style="display: none;"></i><span class="title-content-index c-index-single c-index-single-hot9 c-index-single-hot-new" style="display: ;">9</span><span class="title-content-title">花生这辈子没想到还能被切丝</span></a><span class="title-content-mark ie-vertical c-text c-gap-left-small c-text-hot">热</span></li></ul></div>
"""

result = re.findall('class="title-content-title">(.+?)</span>', html)
for i, r in enumerate(result):
    print(i+1, r)

案例二:错误日志

import re

log_text = """
2026-01-30 10:00:00 INFO 服务启动成功
2026-01-30 10:05:00 ERROR 数据库连接失败,错误码:500
2026-01-30 10:06:00 INFO 用户登录成功,账号:user1
2026-01-30 10:08:00 Exception 数组越界,位置:line 25
2026-01-30 10:10:00 ERROR 接口请求超时,目标地址:/api/data"""

# 正则:匹配含ERROR/Exception的整行日志,re.M开启多行模式
error_pattern = r"^.*(?:ERROR|Exception).*$"
error_logs = re.findall(error_pattern, log_text, flags=re.M)

# 输出结果
print("提取的错误日志:")
for log in error_logs:
    print(log)

案例三:IP地址

import re

text = """服务器IP:192.168.1.1,备用IP:10.0.0.0,测试IP:255.255.255.255
无效IP:256.0.0.1、192.168.1、192.168.01.1、192.168.1.002
混杂内容:123456 172.16.5.88 abc.def.ghi.jkl"""

# 单段合法IP正则(0-255,无前置0)
ip_segment = r"(?:25[0-5]|2[0-4]\d|[01]?\d\d?)"
# 完整合法IPv4正则
ipv4_pattern = rf"{ip_segment}(?:\.{ip_segment}){{3}}"
# 提取所有合法IP
valid_ips = re.findall(ipv4_pattern, text)

print("提取的合法IPv4地址:")
for ip in valid_ips:
    print(ip)

案例四:html文本

import re

html_text = """<h1>Python正则表达式</h1>
<p>这是<b>正则</b>的<em>实战案例</em>,基于Python <span style="color:red">re模块</span>。</p>
<a href="https://python.org" rel="external nofollow" >Python官网</a>"""

pure_text = re.findall(r"<.*?>(.*?)<.*?>", html_text )

print(pure_text)

总结

到此这篇关于正则表达式与re模块的文章就介绍到这了,更多相关正则表达式与re模块内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 正则表达式中最短匹配模式的用法浅析

    正则表达式中最短匹配模式的用法浅析

    最短匹配应用于:假如有一段文本,你只想匹配最短的可能,而不是最长。下面这篇文章主要给大家介绍了关于正则表达式中最短匹配模式用法的相关资料,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-07-07
  • 正则表达式教程之重复匹配详解

    正则表达式教程之重复匹配详解

    这篇文章主要介绍了正则表达式教程之重复匹配,结合实例形式分析了正则表达式重复匹配及防止过度匹配相关技巧,需要的朋友可以参考下
    2017-01-01
  • 正则表达式链接替换函数的技巧

    正则表达式链接替换函数的技巧

    这篇文章给大家介绍正则表达式链接替换函数的技巧,涉及到正则表达式替换相关知识,对正则表达式链接替换函数的技巧感兴趣的朋友一起学习吧
    2015-11-11
  • Notepad+正则表达式使用方法举例详解

    Notepad+正则表达式使用方法举例详解

    使用正则表达式可以很好地完成很多繁琐耗时的工作,下面这篇文章主要给大家介绍了关于Notepad+正则表达式使用方法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-08-08
  • UNIX/LINUX SHELL 正则表达式语法详解附使用方法

    UNIX/LINUX SHELL 正则表达式语法详解附使用方法

    一个正则表达式就是由普通字符(例如字符 a 到 z)以及特殊字符(称为元字符)组成的文字模式。该模式描述在查找文字主体时待匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配
    2019-11-11
  • 手把手教你使用正则表达式验证银行帐号

    手把手教你使用正则表达式验证银行帐号

    银行卡号是一大串的数字,当然具有一定的规则,下面这篇文章主要给大家介绍了关于使用正则表达式验证银行帐号的相关资料,文中给出了详细的实例代码,需要的朋友可以参考下
    2023-03-03
  • js中exec、test、match、search、replace、split用法

    js中exec、test、match、search、replace、split用法

    exec、test、match、search、replace、split在JS中用的很频繁,在网上看到对这些方法的总结,就转过来了,作个记录
    2012-08-08
  • 如何用正则取input type="text"中的value

    如何用正则取input type="text"中的value

    如何用正则取input type="text"中的value...
    2006-10-10
  • 浅谈Linux grep与正则表达式

    浅谈Linux grep与正则表达式

    grep 是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。下面通过本文给大家分享Linux grep与正则表达式的相关知识,感兴趣的朋友一起看看吧
    2017-07-07
  • 取字和字符的长度

    取字和字符的长度

    取字和字符的长度...
    2006-07-07

最新评论