最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

一篇文章精通正則表達(dá)式與re模塊(含案例)

 更新時(shí)間:2026年07月08日 10:49:41   作者:榴蓮終結(jié)者  
正則表達(dá)式就是為了利用特殊符號,快速實(shí)現(xiàn)字符串的匹配,這篇文章主要介紹了正則表達(dá)式與re模塊的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、正則簡介

正則表達(dá)式(Regular Expression,常簡稱 “正則” 或 regex),也叫正規(guī)表示法,本質(zhì)上是一套用來描述文本排列規(guī)則的表達(dá)式。它可以精準(zhǔn)定義字符串的匹配模式,是處理復(fù)雜文本信息的強(qiáng)大工具。

正則表達(dá)式并非 Python 專屬,它是一套獨(dú)立于編程語言的文本處理標(biāo)準(zhǔn),擁有自身獨(dú)特的語法規(guī)則和獨(dú)立的正則引擎。當(dāng)我們用正則語法編寫好匹配規(guī)則(模式)后,引擎不僅能執(zhí)行模糊文本查找,還能完成模糊分割、內(nèi)容替換等復(fù)雜操作,讓開發(fā)者可以靈活高效地處理各類文本信息。多數(shù)編程語言都會(huì)提供操作正則引擎的接口,比如 Python 就內(nèi)置了 re 模塊來實(shí)現(xiàn)正則功能。

盡管在簡單文本處理場景中,正則的效率略遜于編程語言自帶的字符串操作,但它的功能覆蓋面和處理復(fù)雜場景的能力,是普通字符串操作無法比擬的。

正則表達(dá)式最早起源于 Perl 語言,后續(xù)包括 Java、PHP、Go、JavaScript、SQL 在內(nèi)的大多數(shù)編程語言,在實(shí)現(xiàn)正則功能時(shí)都沿用了 Perl 的核心語法。這意味著你在 Python 中學(xué)到的正則知識,幾乎可以無縫遷移到其他語言中,具備極高的通用性。

總的來說,無論是哪種編程語言,對字符串或文本的核心操作都離不開分割、匹配、查找、替換這四類場景,而正則正是為高效解決這些問題而生的工具。

二、元字符

正則表達(dá)式的核心威力,來自于它定義的一系列 “元字符”。這些特殊字符不再代表字面含義,而是被賦予了匹配規(guī)則的功能,是我們構(gòu)建復(fù)雜匹配模式的基礎(chǔ)。

1、通配符

通配符是正則里最基礎(chǔ)的元字符,其中最具代表性的就是英文句號 .

匹配規(guī)則:它可以匹配除了換行符(\n)之外的任意單個(gè)字符。

import re
# . 匹配一個(gè)任意字符(除換行符)
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、字符集

當(dāng)我們希望匹配某一類特定字符,而不是任意字符時(shí),就需要用到字符集(Character Set)。它用方括號 [] 來定義。

匹配規(guī)則:方括號中的任意一個(gè)字符都會(huì)被匹配,且字符集只匹配單個(gè)位置。

import re
# [] 字符集 匹配字符集中的任意一個(gè)字符
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] 等價(jià)于 [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] 等價(jià)于 所有大小寫英文字母
result6 = re.findall("a[a-zA-Z]e", s)
print(result6)  # ['age', 'aze', 'aYe', 'ate']
# [^字符集] 匹配除了字符集中的任意一個(gè)字符
result7 = re.findall("a[^0-9]e", s)
print(result7)  # ['a%e', 'age', 'aze', 'aYe', 'ate', 'a#e', 'a\ne']

進(jìn)階核心用法

  1. 范圍表示:通過連字符 - 表示連續(xù)字符范圍,簡化多字符書寫,[a-z] 匹配任意小寫字母、[0-9] 匹配任意數(shù)字、[A-Za-z0-9_] 匹配任意字母 / 數(shù)字 / 下劃線。

  2. 取反操作:在字符集開頭加脫字符 ^,表示匹配除括號內(nèi)字符外的任意單個(gè)字符,[^0-9] 匹配任意非數(shù)字字符。

3、重復(fù)元字符

在實(shí)際文本處理中,我們常需要匹配連續(xù)出現(xiàn)多次的字符 / 子模式(比如匹配 1 個(gè)或多個(gè)數(shù)字、0 個(gè)或多個(gè)字母),此時(shí)通配符和字符集的單字符匹配能力已無法滿足需求,重復(fù)元字符(量詞元字符) 應(yīng)運(yùn)而生 —— 它可以指定某個(gè)字符 / 子模式的重復(fù)匹配次數(shù),是實(shí)現(xiàn)多字符批量匹配的核心元字符,讓正則匹配規(guī)則從 “單字符” 拓展到 “多字符”。

重復(fù)元字符均為后綴式使用,即緊跟在需要被指定重復(fù)次數(shù)的目標(biāo)字符 / 子模式后,僅對其緊鄰的前一個(gè)匹配單元生效。

(1):{}

{n,m}:數(shù)量范圍貪婪符,指定左邊原子的數(shù)量范圍,有{n},{n,},{m},{n,m}四種寫法,其中n與m必須是非負(fù)整數(shù)

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} 表示任意字符出現(xiàn)3次 即.重復(fù)三次
result2 = re.findall("a.{3}e", s)
print(result2)  # ['aeeee', 'apple', 'agree', 'amaze']
# .{1,3} 表示任意字符出現(xiàn)1到3次,貪婪匹配,按著最大的匹配數(shù)去匹配
result3 = re.findall("a.{1,3}e", s)
print(result3)  # ['aeeee', 'apple', 'a%e', 'a9e', 'agree', 'age', 'amaze', 'aYe', 'ate', 'a1e', 'a#e', 'adve']
# 如何取消貪婪匹配 加上?,取消貪婪匹配,按著最小的匹配數(shù)去匹配
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,} 表示任意字符出現(xiàn)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,}? 表示任意字符出現(xiàn)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} 表示任意小寫字母出現(xiàn)1到4次
result6 = re.findall("a[a-z]{1,4}e", s)
print(result6)  # ['aeeee', 'apple', 'agree', 'age', 'amazee', 'ate', 'adve']

(2):*

*指定左邊原子出現(xiàn)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):+

+指定左邊原子出現(xiàn)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):?

?指定左邊原子出現(xiàn)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):總結(jié)

常用核心重復(fù)元字符

重復(fù)元字符 核心匹配規(guī)則簡單示例示例匹配結(jié)果
{n}匹配前一個(gè)單元恰好 n 次(n 為非負(fù)整數(shù))a{3}b僅匹配aaab
{n,}匹配前一個(gè)單元至少 n 次(n 次及以上)a{2,}baab、aaabaaaab(不匹配ab、b
{n,m}匹配前一個(gè)單元n 到 m 次(包含 n 和 m,n≤m)a{1,3}bab、aabaaab(不匹配b、aaaab
*匹配前一個(gè)單元0 次或任意多次(0 次即允許不出現(xiàn))a*bb、ab、aab、aaab
+匹配前一個(gè)單元1 次或任意多次(至少出現(xiàn) 1 次)a+babaab、aaab(不匹配b
?匹配前一個(gè)單元0 次或 1 次(最多出現(xiàn) 1 次,可選)a?bbab(不匹配aab

貪婪匹配 vs 非貪婪匹配

重復(fù)元字符默認(rèn)采用貪婪匹配策略,即盡可能匹配最多的符合規(guī)則的字符;若在重復(fù)元字符后追加一個(gè)?,則會(huì)切換為非貪婪匹配,即盡可能匹配最少的符合規(guī)則的字符。

匹配模式語法形式核心策略示例正則待匹配字符串匹配結(jié)果
貪婪匹配a{1,3}取最大允許次數(shù)匹配a{1,3}aaaaaaaa
非貪婪匹配a{1,3}? 取最小允許次數(shù)匹配a{1,3}?a

4、^和$

在正則匹配中,我們常會(huì)遇到精準(zhǔn)匹配整行內(nèi)容、限定字符出現(xiàn)位置的需求(比如匹配純數(shù)字的手機(jī)號、純字母的用戶名,而非字符串中夾雜的數(shù)字 / 字母片段),此時(shí)就需要用到邊界匹配元字符^$是最核心的一對行邊界匹配元字符,專門用于限定字符串 / 行的開頭和結(jié)尾,讓匹配規(guī)則從 “模糊查找片段” 升級為 “精準(zhǔn)匹配整體”。

^$本身不匹配任何具體字符,僅用于標(biāo)記位置,屬于 “零寬匹配” 元字符(匹配結(jié)果不占字符長度),二者常配合使用實(shí)現(xiàn)整行精準(zhǔn)匹配,也可單獨(dú)使用限定單邊位置。

import re

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

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

^$組合使用是實(shí)際開發(fā)中最常用的方式,核心解決 **“純內(nèi)容匹配”** 問題,避免匹配到夾雜目標(biāo)內(nèi)容的無效字符串,這是正則實(shí)現(xiàn)精準(zhǔn)校驗(yàn)的基礎(chǔ),典型實(shí)用場景如下:

import re

# 校驗(yàn)純 11 位手機(jī)號(僅數(shù)字校驗(yàn),簡易版)
s1 = '13800138000'
s2 = '13800138000 '
print(re.findall(r'^[0-9]{11}$', s1))  # ['13800138000']
print(re.findall(r'^[0-9]{11}$', s2))  # []
# 校驗(yàn)僅由字母 / 數(shù)字組成的 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 模塊的行匹配擴(kuò)展:re.MULTILINE 標(biāo)志

默認(rèn)情況下,^僅匹配整個(gè)字符串的開頭,$僅匹配整個(gè)字符串的結(jié)尾,即使字符串包含多個(gè)換行符(\n),也不會(huì)將每行單獨(dú)作為匹配單元。

若需要對多行字符串實(shí)現(xiàn) “按行匹配”(即^匹配每行開頭、$匹配每行結(jié)尾),可在 re 模塊函數(shù)中指定 **re.MULTILINE(簡寫re.M)** 標(biāo)志,這一特性在處理日志、文本文件等多行內(nèi)容時(shí)尤為實(shí)用。

import re

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

# 無re.M標(biāo)志:默認(rèn)匹配整個(gè)字符串開頭,僅能找到1個(gè)結(jié)果
default_result = re.findall(r"^[0-9]{3}", multi_text)
print("默認(rèn)匹配結(jié)果:", default_result)  # ['123']

# 加re.M標(biāo)志:按行匹配,每行開頭的3位數(shù)字都能被匹配
multi_result = re.findall(r"^[0-9]{3}", multi_text, flags=re.M)
print("按行匹配結(jié)果:", multi_result)  # ['123', '456', '789']

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

注意:與字符集內(nèi) ^ 的區(qū)別:字符集[]內(nèi)的^取反操作(如[^0-9]匹配非數(shù)字),而單獨(dú)使用的^開頭邊界匹配,二者語法位置不同,含義完全無關(guān),切勿混淆;

5、轉(zhuǎn)義符 \

正則中的轉(zhuǎn)義符和Python字符串的轉(zhuǎn)義符相似,兩個(gè)功能

(1):為普通字符賦予特殊含義

元字符說明
\d匹配數(shù)字,等于[0-9]
\D匹配非數(shù)字,等于[^0-9]或[^\d]
\w匹配單詞字符(字母、數(shù)字、下劃線),等于[0-9a-zA-Z_]
\W匹配非單詞字符,等于[^0-9a-zA-Z_]或[^\w]
\s匹配空白字符(空格、制表符等)
\S匹配非空白字符
\n匹配換行符
\t匹配制表符,tab鍵
\s匹配一個(gè)任何空白字符原子,包括空格、制表符、換頁符等等。
\S匹配一個(gè)任何非空白字符原子。
\b匹配一個(gè)單詞邊界原子,也就是指單詞和空格間的位置。
\B匹配一個(gè)非單詞邊界原子,等價(jià)于[^\b]
import re

s1 = "wjh\nage 24 shengao 185 gender m price 9999 birthday! 0109"
# \d	匹配數(shù)字,等于[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	匹配非數(shù)字,等于[^0-9]或[^\d]
print(re.findall(r"\D+", s1))  # ['wjh\nage ', ' shengao ', ' gender men price ', ' birthday! ']
# \w	匹配單詞字符(字母、數(shù)字、下劃線),等于[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	匹配一個(gè)單詞邊界原子,也就是指單詞和空格間的位置。
print(re.findall(r"\bcat\b", s2))  # ['cat', 'cat'] 只有cat和cat!能匹配
# \B	匹配一個(gè)非單詞邊界原子,等價(jià)于[^\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/,因?yàn)閣ww后面有兩個(gè)w,所以我們需要使用轉(zhuǎn)義符
"""
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、()分組與優(yōu)先提取

在正則的實(shí)際使用中,我們會(huì)發(fā)現(xiàn)僅靠單字符 / 單一匹配單元的組合,無法滿足多字符整體重復(fù)、多規(guī)則分支匹配、匹配結(jié)果精準(zhǔn)提取的需求(比如匹配ab重復(fù) 3 次、匹配手機(jī)號/郵箱二選一、從匹配結(jié)果中單獨(dú)提取數(shù)字部分)。

此時(shí)分組元字符() 成為核心解決方案 —— 它能將括號內(nèi)的任意字符 / 子模式包裹為一個(gè)獨(dú)立的匹配單元(分組),讓重復(fù)、邊界等元字符對整個(gè)分組生效;同時(shí)分組還支持優(yōu)先提取匹配結(jié)果,能從整體匹配內(nèi)容中精準(zhǔn)拆分出我們需要的子內(nèi)容,是正則從 “基礎(chǔ)匹配” 升級為 “復(fù)雜場景匹配 + 結(jié)果解析” 的關(guān)鍵元字符。

(1):構(gòu)建獨(dú)立匹配單元

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):優(yōu)先提取匹配結(jié)果

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. 普通捕獲分組 ():僅分組,也會(huì)捕獲
# (ab){2} 把a(bǔ)b設(shè)為整體重復(fù)2次,但()會(huì)讓findall優(yōu)先返回分組內(nèi)的ab
capture_res = re.findall(r"(ab){2}", text)
print("普通捕獲分組結(jié)果:", capture_res)  # 輸出:['ab', 'ab'](只返回分組內(nèi)的ab,而非完整的abab)

# 2. 非捕獲分組 (?:):僅分組,不捕獲
# (?:ab){2} 僅把a(bǔ)b設(shè)為整體重復(fù)2次,不捕獲,findall返回完整匹配結(jié)果
non_capture_res = re.findall(r"(?:ab){2}", text)
print("非捕獲分組結(jié)果:", non_capture_res)  # 輸出:['abab', 'abab'](直接返回完整的abab,符合需求)

7、分支元字符|

在正則匹配的實(shí)際場景中,我們常遇到多規(guī)則任選其一匹配的需求,比如匹配手機(jī)號或固定電話、匹配郵箱或用戶名、匹配中文或英文名稱,此時(shí)單一的匹配規(guī)則已無法滿足需求,分支元字符| 應(yīng)運(yùn)而生。

import re

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

s2 = "聯(lián)系電話:13800138000 辦公電話:010-12345678 無效號碼:123456"
# 正則:(\d{11})|(\d{3}-\d{7,8})  兩個(gè)分組分支,分別匹配手機(jī)號、固定電話
result1 = re.findall(r"(\d{11})|(\d{3}-\d{7,8})", s2)
# 處理結(jié)果:過濾元組中的空值,提取有效匹配
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固定,分組內(nèi)分支匹配后綴可選規(guī)則
result2 = re.findall(r"py(thon|charm|game)", s3)
print(result2)  # ['thon', 'charm', 'game', 'thon'](僅提取分組內(nèi)分支內(nèi)容)
# 若需提取完整單詞,將整個(gè)規(guī)則設(shè)為非捕獲分組或整體匹配
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"  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"  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">中非攜手共逐發(fā)展振興夢</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"  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">何猷君當(dāng)選新職</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"  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"  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">解放軍軍機(jī)飛進(jìn)菲軍演劃設(shè)區(qū)</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"  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"  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">均價(jià)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"  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">刷新多項(xiàng)紀(jì)錄!中國在多領(lǐng)域?qū)崿F(xiàn)突破</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"  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"  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個(gè)月下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"  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)

案例二:錯(cuò)誤日志

import re

log_text = """
2026-01-30 10:00:00 INFO 服務(wù)啟動(dòng)成功
2026-01-30 10:05:00 ERROR 數(shù)據(jù)庫連接失敗,錯(cuò)誤碼:500
2026-01-30 10:06:00 INFO 用戶登錄成功,賬號:user1
2026-01-30 10:08:00 Exception 數(shù)組越界,位置:line 25
2026-01-30 10:10:00 ERROR 接口請求超時(shí),目標(biāo)地址:/api/data"""

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

# 輸出結(jié)果
print("提取的錯(cuò)誤日志:")
for log in error_logs:
    print(log)

案例三:IP地址

import re

text = """服務(wù)器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
混雜內(nèi)容: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正則表達(dá)式</h1>
<p>這是<b>正則</b>的<em>實(shí)戰(zhàn)案例</em>,基于Python <span style="color:red">re模塊</span>。</p>
<a  rel="external nofollow" >Python官網(wǎng)</a>"""

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

print(pure_text)

總結(jié)

到此這篇關(guān)于正則表達(dá)式與re模塊的文章就介紹到這了,更多相關(guān)正則表達(dá)式與re模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 正則表達(dá)式中最短匹配模式的用法淺析

    正則表達(dá)式中最短匹配模式的用法淺析

    最短匹配應(yīng)用于:假如有一段文本,你只想匹配最短的可能,而不是最長。下面這篇文章主要給大家介紹了關(guān)于正則表達(dá)式中最短匹配模式用法的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-07-07
  • 正則表達(dá)式教程之重復(fù)匹配詳解

    正則表達(dá)式教程之重復(fù)匹配詳解

    這篇文章主要介紹了正則表達(dá)式教程之重復(fù)匹配,結(jié)合實(shí)例形式分析了正則表達(dá)式重復(fù)匹配及防止過度匹配相關(guān)技巧,需要的朋友可以參考下
    2017-01-01
  • 正則表達(dá)式鏈接替換函數(shù)的技巧

    正則表達(dá)式鏈接替換函數(shù)的技巧

    這篇文章給大家介紹正則表達(dá)式鏈接替換函數(shù)的技巧,涉及到正則表達(dá)式替換相關(guān)知識,對正則表達(dá)式鏈接替換函數(shù)的技巧感興趣的朋友一起學(xué)習(xí)吧
    2015-11-11
  • Notepad+正則表達(dá)式使用方法舉例詳解

    Notepad+正則表達(dá)式使用方法舉例詳解

    使用正則表達(dá)式可以很好地完成很多繁瑣耗時(shí)的工作,下面這篇文章主要給大家介紹了關(guān)于Notepad+正則表達(dá)式使用方法的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-08-08
  • UNIX/LINUX SHELL 正則表達(dá)式語法詳解附使用方法

    UNIX/LINUX SHELL 正則表達(dá)式語法詳解附使用方法

    一個(gè)正則表達(dá)式就是由普通字符(例如字符 a 到 z)以及特殊字符(稱為元字符)組成的文字模式。該模式描述在查找文字主體時(shí)待匹配的一個(gè)或多個(gè)字符串。正則表達(dá)式作為一個(gè)模板,將某個(gè)字符模式與所搜索的字符串進(jìn)行匹配
    2019-11-11
  • 手把手教你使用正則表達(dá)式驗(yàn)證銀行帳號

    手把手教你使用正則表達(dá)式驗(yàn)證銀行帳號

    銀行卡號是一大串的數(shù)字,當(dāng)然具有一定的規(guī)則,下面這篇文章主要給大家介紹了關(guān)于使用正則表達(dá)式驗(yàn)證銀行帳號的相關(guān)資料,文中給出了詳細(xì)的實(shí)例代碼,需要的朋友可以參考下
    2023-03-03
  • js中exec、test、match、search、replace、split用法

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

    exec、test、match、search、replace、split在JS中用的很頻繁,在網(wǎng)上看到對這些方法的總結(jié),就轉(zhuǎn)過來了,作個(gè)記錄
    2012-08-08
  • 如何用正則取input type="text"中的value

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

    如何用正則取input type="text"中的value...
    2006-10-10
  • 淺談Linux grep與正則表達(dá)式

    淺談Linux grep與正則表達(dá)式

    grep 是一種強(qiáng)大的文本搜索工具,它能使用正則表達(dá)式搜索文本,并把匹配的行打印出來。下面通過本文給大家分享Linux grep與正則表達(dá)式的相關(guān)知識,感興趣的朋友一起看看吧
    2017-07-07
  • 取字和字符的長度

    取字和字符的長度

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

最新評論

漯河市| 安康市| 瓮安县| 漳州市| 巴彦淖尔市| 济阳县| 托里县| 靖宇县| 卫辉市| 泾川县| 金秀| 偃师市| 山丹县| 岑巩县| 织金县| 衡南县| 保靖县| 长泰县| 六安市| 安国市| 河北区| 湖北省| 青田县| 水富县| 冷水江市| 宜兴市| 平乡县| 焦作市| 特克斯县| 固镇县| 阆中市| 九龙城区| 如皋市| 株洲县| 若尔盖县| 沭阳县| 禄丰县| 庆城县| 青浦区| 五家渠市| 天津市|