目錄
- 一、認識正則表達式
- 二、正則表達式基本語法
- 2.1 行界定符
- 2.2 單詞定界符
- 2.3 字符類
- 2.4 選擇符
- 2.5 范圍符
- 2.6 排除符
- 2.7 限定符
- 2.8 任意字符
- 2.9 轉義字符
- 2.10 反斜杠
- 2.11 小括號
- 2.11.1 定義獨立單元
- 2.11.2 分組
- 2.12 反向引用
- 2.13 特殊構造
- 2.14 匹配模式
- 三、re模塊
- 3.1 compile()方法——編譯為正則表達式對象
- 3.2 escape()方法——轉義特殊字符
- 3.3 f?indall()方法——搜索所有符合正則表達式的字符串
- 3.4 f?inditer()方法——找到所匹配的所有子串
- 3.5 fullmatch()方法——對整個字符串進行匹配
- 3.6 match()方法——從字符開始處進行匹配
- 3.7 search()方法——搜索第一個匹配位置
- 3.8 split()方法——根據正則表達式分割字符串
- 3.9 sub()方法——字符串替換
- 3.10 subn()方法——字符串替換 (含替換次數)
- 3.11 Pattern的屬性以及方法
- 3.11.1 Pattern.flags屬性——獲取正則匹配標記
- 3.11.2 Pattern.groups屬性——捕獲組合的數量
- 3.11.3 Pattern.groupindex屬性——獲取分組名稱與對應的分組編號
- 3.11.4 Pattern.pattern屬性——獲取模式字符串
- 3.11.5 Pattern.f?indall()方法——搜索所有符合正則表達式的字符串
- 3.11.6 Pattern.f?inditer()方法——搜索所匹配的所有子串
- 3.11.7 Pattern.fullmatch()方法——對整個字符串匹配
- 3.11.8 Pattern.match()方法——從字符開始處匹配字符串的值
- 3.11.9 Pattern.search()方法——搜索第一個匹配的位置
- 3.11.10 Pattern.split()方法——同split()方法
- 3.11.11 Pattern.sub()方法——字符串替換
- 3.11.12 Pattern.subn()方法——字符串替換(含替換次數)
- 3.12 Match對象屬性及方法
- 3.12.1 Match.endpos屬性——結束匹配的索引位置
- 3.12.2 Match.pos屬性——開始匹配的索引位置
- 3.12.3 Match.lastindex屬性——捕獲組的最后一個匹配的索引值
- 3.12.4 Match.lastgroup屬性——獲取最后一個匹配組的名稱
- 3.12.5 Match.re屬性——返回正則表達式對象
- 3.12.6 Match.string屬性——獲取需要匹配的字符串
- 3.12.7 Match.`__getitem__()` 方法——返回一個匹配的分組信息
- 3.12.8 Match.end()方法——返回分組匹配字符串對應的結束標記
- 3.12.9 Match.expand()方法——對“\”進行轉義替換并返回
- 3.12.10 Match.groups()方法——以元組形式返回所有子組中內容
- 3.12.11 Match.group()方法——返回一個或者多個匹配的子組
- 3.12.12 Match.groupdict()方法——返回包含所有匹配值分組的字典
- 3.12.13 Match.span()方法——返回包含開始和結束位置的二元組
- 3.12.14 Match.start()方法——返回分組匹配字符串對應的開始標記
- 四、練習
正則表達式是非常強大的字符串操作工具,其語法形式為一個特殊的字符序列,常用來對字符串進行匹配操作。Python 從 1.5 版本開始新增 re 模塊,提供 Perl 風格的正則表達式支持。本文將詳細介紹正則表達式的基本語法,以及 Python 正則表達式標準庫的基本用法。
【學習重點】
- 了解正則表達式的相關概念。
- 掌握正則表達式的基本語法。
- 熟悉 Python 的 re 模塊。
- 能夠使用正則表達式解決實際問題。
一、認識正則表達式
正則表達式又稱規則表達式(Regular Expression),在代碼中簡寫為 regex、regexp 或 RE,通常被用來匹配符合指定模式(規則)的文本。現代計算機編程語言都支持利用正則表達式進行字符串操作。實際上,正則表達式就是一種邏輯模板,是用事先定義好的一組特定字符,以及這些特定字符的任意組合,組成一個 "正則表達式字符串"
, 這個 "正則表達式字符串"
用來表達對字符串的一種過濾邏輯。
給定一個正則表達式和一個被操作的字符串,可以達到以下目的:
- 驗證被操作字符串是否符合正則表達式的匹配邏輯。
- 通過正則表達式,從被操作字符串中獲取特定的信息,或者修改字符串。
Python 支持 Perl 風格的正則表達式語法。下面先了解與正則表達式相關的幾個概念:
- grep:grep 是一種強大的文本搜索工具,它能使用特定模式匹配(包括正則表達式)搜索文本,并默認輸出匹配行。
- egrep:由于 grep 更新的速度無法與技術更新的速度同步。為此,貝爾實驗室推出了 egrep,即擴展的 grep,這大大增強了正則表達式的能力。
- POSIX:在 grep 發展的同時,其他一些開發人員也根據自己的喜好開發出了具有獨特風格的版本。但問題也隨之而來,有的程序支持某個元字符,而有的程序則不支持,因此就有了 POSIX。POSIX 是一系列標準,確保了操作系統之間的可移植性。但 POSIX 和 SQL 一樣沒有成為最終的標準,而只能作為一個參考。
- Perl: 1987年,Larry Wall 發布了 Perl 編程語言,它汲取了多種語言精華,并內部集成了正則表達式的功能,以及巨大的第三方代碼庫 CPAN。Perl 經歷了從 Perl 1 到現在 Perl 6 的發展最終成了 POSIX 之后的另一個標準。
- PCRE:1997 年,Philip Hazel 開發了 PCRE 庫,它是能夠兼容 Perl 正則表達式的一套正則引擎,其他開發人員可以將 PCRE 整合到自己的語言中,為用戶提供豐富的正則功能。
參考:https://www.w3cschool.cn/regex_rmjc/
分類:
1.BRE。基本正則表達式,grep、sed、vi等軟件支持。vim有擴展。
2.ERE。擴展正則表達式,egrep(grep -E)、sed -r等。
3.PCRE。幾乎所有高級語言都是PCRE的方言或者變種。Python從1.6開始使用SRE正則表達式引擎,可以認為是PCRE的子集,見模塊re。
二、正則表達式基本語法
在形式語言理論中,正則表達式被稱為 "規則語言"
,而不是編程語言。在 Python 中,"正則表達式"
這個概念包含兩層含義:一個是正則表達式字符串;另一個是正則表達式對象。正則表達式字符串是正則表達式的文本表示,它經過編譯后就成為正則表達式對象。正則表達式對象具有匹配功能。正則表達式字符串由兩部分構成:元字符和普通字符。元字符是具有特殊含義的字符,如 "."
和 "?"
,普通字符是僅指代自身的普通字符,如數字、字母等。本小節將詳細介紹各種元字符的含義和用法。
由于在這里我們還沒有學習 re 模塊,我們通過一個工具來學習正則表達式的基本語法,如下圖所示:
軟件下載地址:
通過網盤分享的文件:正則表達式
鏈接: https://pan.baidu.com/s/1TeYRnx1QkgHY6rfxlSQ9Jw?pwd=1946 提取碼: 1946
--來自百度網盤超級會員v9的分享網盤中帶有一些正則表達式的文檔資料,不需要可以直接下載 正則表達式編寫及調試工具.msi 軟件
2.1 行界定符
行界定符描述一行字符串的邊界,具體說明如下:
^: 表示行的開始
$: 表示行的結尾
在多行匹配模式中,行定界符能夠匹配每一行的行首和行尾位置。① 單行模式: .可以匹配所有字符,包括換行符,^ 表示整個字符串的開頭,$整個字符串的結尾
② 多行模式: .可以匹配除了換行符之外的字符,多行不影響.點號。^ 表示行首,$行尾,只不過這里的行是每一個行 ? re.MULTILINE
③ 默認模式: 可以看做待匹配的文本是一行,不能看做多行,.點號不能匹配換行符,^和$表示行首和行尾,
而行首行尾就是整個字符串的開頭和結尾
④ 單行模式: 基本和默認模式一樣,只是.點號終于可以匹配任意一個字符包括換行符,這時所有文本就是一個長長的只有一行的字符串。
^就是這一行字符串的行首,$就是這一行的行尾。⑤ 多行模式: 重新定義了行的概念,但不影響.點號的行為,^和$還是行首行尾的意思,只不過因為多行模式可以識別換行符了。
"開始"指的是\n后緊接著下一個字符;"結束"指的是\n前的字符,注意最后一行結尾可以沒有\n
簡單講,單行模式只影響.點號行為,多行模式重新定義行影響了^和$
注意: 注意字符串中看不見的換行符,\r\n會影響e$的測試,e$只能匹配e\n
示例1:.$
指的是此行的結尾,而默認模式和單行模式都是一行,指的是這個大字符串的最后一個字符,就是 key 的 y。如下圖所示:
示例2:上面第一行 happy 之后,有可能是 \r\n
結尾。y$
單行匹配 key 的 y,多行匹配 happy 和 key 的 y。如下圖所示:
注意: 都是選擇 全部匹配
進行測試。如果選擇 匹配
,則默認只匹配一次,即使是多行模式,也只會匹配上一個 y。如下圖所示:
2.2 單詞定界符
單詞定界符描述一個單詞的邊界,具體說明如下:
\b: 表示單詞邊界
\B: 表示非單詞邊界ps: 在正則表達式中,單詞是由26個字母(含大小寫)和10個數字組成的任意長度且連續的字符串。
單詞與非單詞類字符相鄰的位置稱為單詞邊界。
示例1:使用 \b
定界符匹配一個完整的 "htm"
單詞。如下圖所示:
2.3 字符類
字符類也稱為字符集,就是一個字符列表,表示匹配字符列表中的任意一個字符。使用方括號([…])可以定義字符類。例如,[abc],可以匹配 a、b、c 中的任意一個字母。
示例1:下面正則表達式定義了匹配 html、HTML、Html、hTml 或 HTml 的字符類。
所有的特殊字符在字符集中都失去了其原有的特殊含義,僅表示字符本身。在字符集中如果要使用 [
、]
、-
或 ^
,可以在 [
、]
、-
或 ^
字符前面加上反斜杠,或者把 [
、]
和 -
放在字符集中第 1 個字符位置,把 ^
放在非第 1 個字符位置。下圖正則表達式可以匹配一些特殊字符:
2.4 選擇符
選擇符類似字符類,可以實現選擇性匹配。使用 "|"
可以定義選擇匹配模式,類似 Python 運算中的邏輯或。"|"
代表左右表達式任意匹配一個,它總是先嘗試匹配左側的表達式,一旦成功匹配,則跳出匹配右邊的表達式。如果 "|"
沒有被包括在小括號中,則它的匹配范圍是整個正則表達式。
示例1:下面字符模式可以匹配 html,也可以匹配 Html。
加小括號,如下圖所示:
2.5 范圍符
使用字符類需要列舉所有可選字符,當可選字符比較多時就比較麻煩。不過,在字符類中可以使用連字符 "-"
定義字符范圍。連字符左側字符為范圍起始點,右側字符為范圍終止點。字符范圍都是根據字符編碼表的位置關系來確定的。示例:
'[a-z]' # 匹配任意一個小寫字母
'[A-Z]' # 匹配任意一個大寫字母
'[0-9]' # 匹配任意一個數字
'[\u4e00-\u9fa5]' # 匹配中文字符
'[\x00-\xff]' # 匹配單字節字符
'[a-zA-Z0-9\u4e00-\u9fa5\x00-\xff]' # 也可以連著寫
2.6 排除符
在字符類中,除了范圍符外,還有一個元字符:排除符 (^
)。將 '^'
放到方括號內最左側,表示排除字符列表,也就是將反轉該集合的意義。類似 Python 運算中的邏輯非。示例:
'[^0-9]' # 匹配任意一個非數字
'[^\x00-\xff]' # 匹配非單字節字符
2.7 限定符
限定符也稱為數量詞,用來指定正則表達式的一個給定字符、字符類或子表達式必須要出現多少次才能滿足匹配。具體說明如下表所示:
2.8 任意字符
點號("."
)能夠匹配除換行符 "\n"
之外的任何單字符。如果要匹配點號("."
)自己,需要使用 "\"
進行轉義。注意: 在 re.DOTALL 模式下也能夠匹配換行符。
示例:使用點號元字符匹配字符串 "gooooooogle"
中前面 6 個字符。
2.9 轉義字符
轉義字符 "\"
能夠將特殊字符變為普通字符,如 "./*/^/$"
等,其功能與 Python 字符串中的轉義字符類似。如果把特殊字符放在中括號內定義字符集,也能夠把特殊字符變成普通字符,如 [*]
等效于 \*
,都可以用來匹配字符 *
。
2.10 反斜杠
反斜杠字符 "\"
除了能夠轉義之外,還具有其他功能,具體說明如下:
- 定義非打印字符,具體說明如下表所示:
- 預定義字符集,具體說明如下表所示:
- 定義斷言的限定符,具體說明如下表所示:
2.11 小括號
在正則表達式中,小括號有兩個作用,簡單說明如下。
2.11.1 定義獨立單元
小括號可以改變選擇符和限定符的作用范圍。示例:
'(h|H)html'
'(goo){1,3}'
在上面代碼中,第 1 行正則表達式定義選擇符范圍為兩個字符,而不是整個正則表達式;第 2 行正則表達式定義限定符限定的是 3 個字符,而不僅僅是左側的第一個字符。
2.11.2 分組
小括號的第 2 個作用就是分組,即定義子表達式,子表達式相當于一個獨立的正則表達式,后面要學到的反向引用與子表達式有直接的關系。子表達式能夠臨時存儲其匹配的字符,然后可以在后面進行引用。正則表達式允許多次分組、嵌套分組,從表達式左邊開始,第一個左括號 "("
的編號為1,然后每遇到一個分組的左括號 "("
,編號就加1。例如:
'(a(b(c)))'
上面表達式中,編號1的子表達式為abc,編號2的子表達式為bc,編號3的子表達式為c。除了默認的編號外,也可以為分組定義一個別名。語法格式如下:
(?P<name>...)
# 例如下面的表達式可以匹配字符串 abcabcabc
(?P<id>abc){3}
2.12 反向引用
在正則表達式,如果遇到分組,將導致子表達式匹配的字符被存儲到一個臨時緩沖區中,所捕獲的每個子匹配都按照正則表達式中從左至右的順序進行編號,從 1 開始,連續編號直至最大 99 個子表達式。每個緩沖區都可以使用 "\n"
訪問,其中 n
為一個標識特定緩沖區的編號。示例:
對于正則表達式 "([ab])\1"
,子表達式 "[ab]"
,雖然可以匹配 'a'
或者 'b'
,但是捕獲組一旦匹配成功,反向引用的內容也就確定了。如果捕獲組匹配到 'a'
,那么反向引用也只能匹配 'a'
,同理,如果捕獲組匹配到 'b'
,那么反向引用也只能匹配 'b'
。由于后面反向引用 '\1'
的限制,要求必須是兩個相同的字符,在這里也就是 'aa'
或者 'bb'
才能匹配成功。
2.13 特殊構造
小括號不僅可以分組,也可以構造特殊的結構,具體說明如下:
-
使用下面語法可以設計小括號不分組,僅作為獨立單元用于
'|'
或重復匹配。(?:...) # 例如,下面表達式僅用于界定邏輯作用范圍,不用來分組 (?:\w)* # 匹配0個或多個單詞字符 (?:html|htm) # 匹配html,或者匹配htm
-
定義匹配模式,使用下面語法可以定義表達式的匹配模式。
(?aiLmsux)正則表達式字符串 aiLmsux 中的每個字符代表一種匹配模式,具體說明參考 2.14 匹配模式 小節介紹 (?aiLmsux)只能夠用在正則表達式的開頭,可以多選。例如,下面表達式可以匹配a,也可以匹配A. (?i)a
-
注釋:使用下面語法可以在正則表達式中添加注釋信息,
"#"
后面的文本作為注釋內容將被忽略掉。(?#注釋信息) 例如,在下面表達式中添加一句注釋,以便表達式閱讀和維護 a(?#匹配字符 abc)bc 上面表達式僅匹配字符串abc,小括號內的內容將被忽略
-
正前瞻,使用下面語法可以定義表達式后面必須滿足特定的匹配條件。
(?=...) # 例如,下面表達式僅匹配后面包含數字的字母a a(?=\d) # 后向匹配僅作為一個限定條件,其匹配的內容不作為表達式的匹配結果。
-
負前瞻:使用下面語法可以定義表達式后面必須不滿足特定的匹配條件。
(?!...) # 例如,下面表達式僅匹配后面不包含數字的字母a a(?!\d) # 后向不匹配僅作為一個限定條件,其匹配的內容不作為表達式的匹配結果。
-
正回顧:使用下面語法可以定義表達式前面必須滿足特定的匹配條件。
(?<=...) # 例如,下面表達式僅匹配前面包含數字的字母a (?<=\d)a # 前向匹配僅作為一個限定條件,其匹配的內容不作為表達式的匹配結果。
-
負回顧:使用下面語法可以定義表達式前面必須不滿足特定的匹配條件。
(?<!...) # 例如,下面表達式僅匹配前面不包含數字的字母a (?<!\d)a # 前向不匹配僅作為一個限定條件,其匹配的內容不作為表達式的匹配結果。
-
條件匹配:使用下面語法可以定義條件匹配表達式。
(?(id/name)yes-pattern|no-pattern) id: 表示分組編號 name: 表示分組的別名,如果對應的分組匹配到字符,則選擇 yes-pattern子表達式執行匹配 如果對應的分組沒有匹配字符,則選擇 no-pattern 子表達式執行匹配 |no-pattern: 可以省略,直接寫成語法: (?(id/name)yes-pattern)
2.14 匹配模式
正則表達式可以包含一些可選的標志修飾符,用來控制匹配的模式。修飾符主要用來調整正則表達式的解釋,擴展正則表達式在匹配、替換等操作時的某些功能,增強了正則表達式的能力。不同的語言都有自己的模式設置,Python 中的主要模式修飾符說明如下表所示:
這些標志修飾符主要用在正則表達式處理函數的 flag 參數中,為可選參數。多個標志可以通過按位 OR(|) 來指定,如 re.I|re.M
,被設置成 I 和 M 標志。
三、re模塊
Python 提供了 re 模塊用于實現正則表達式的操作。在實現時,可以使用 re 模塊提供的方法,如 search()、match()、findall() 等,進行字符串處理,也可以先使用 re 模塊的 compile() 方法將模式字符串轉換為正則表達式對象,然后再使用該正則表達式對象的相關方法來操作字符串。re 模塊在使用時,需要先用 import 語句引入,具體代碼如下:
import re
3.1 compile()方法——編譯為正則表達式對象
compile() 方法用于編譯正則表達式模式,返回一個對象的模式。然后可以通過 RegexObject 對象調用 match() 和 search() 等方法。語法格式如下:
In [7]: re.compile?
Signature: re.compile(pattern, flags=0)
Docstring: Compile a regular expression pattern, returning a Pattern object.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 編譯時用的表達式字符串。
2.flags: 編譯標志位,用于修改正則表達式的匹配方式,如是否區分大小寫、多行匹配等。
3.返回值: 返回一個正則表達式對象。
示例:查找包含指定字母的單詞。使用compile()方法創建一個可以查找包含指定字母對應單詞的正則表達式對象,并輸出符合條件的英文單詞,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊# 需要匹配的字符串
string = "Tina is a good girl, she is cool, clever, and so on..."
match = re.compile(r'\w*oo\w*') # 創建正則表達式對象
print(match.findall(string)) # 打印所有包含"oo"的單詞
3.2 escape()方法——轉義特殊字符
escape() 方法用于對字符串中的非字母數字進行轉義。語法格式如下:
In [8]: re.escape?
Signature: re.escape(pattern)
Docstring: Escape special characters in a string.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示模式字符串,由要匹配的正則表達式轉換而來。
2.返回值: 返回轉義后的字符串。
示例:對字符串中的非字母數字進行轉義。使用escape()方法實現對字符串中的非字母數字進行轉義,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊# 需要轉義的字符串
string = 'abcdefghijklmnopqrstuvwxyz0123456789!#$%&*+-.^_`|~'
# abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&\*\+\-\.\^_`\|\~
print(re.escape(string)) # 打印轉義后的字符串
3.3 f?indall()方法——搜索所有符合正則表達式的字符串
findall() 方法用于在整個字符串中搜索所有符合正則表達式的字符串,并以列表的形式返回。如果匹配成功,則返回包含匹配結構的列表,否則返回空列表。語法格式如下:
In [9]: re.findall?
Signature: re.findall(pattern, string, flags=0)
Docstring:
Return a list of all non-overlapping matches in the string.If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.Empty matches are included in the result.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示模式字符串,由要匹配的正則表達式轉換而來。
2.string: 表示要匹配的字符串。
3.flags: 可選參數,表示標志位,用于控制匹配方式,如是否區分字母大小寫。
4.返回值: 返回一個符合表達式匹配結果的列表。
示例:搜索以“mr_”開頭的字符串。使用findall()方法搜索以“mr_”開頭的字符串,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = r'mr_\w+' # 模式字符串
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.findall(pattern, string, re.I) # 搜索字符串,不區分大小寫
print(match) # 打印匹配結果 ['MR_SHOP', 'mr_shop']
string = '項目名稱MR_SHOP mr_shop'
match = re.findall(pattern, string) # 搜索字符串,區分大小寫
print(match) # 打印匹配結果 ['mr_shop']
3.4 f?inditer()方法——找到所匹配的所有子串
finditer() 方法和 findall() 方法類似,它的功能為在字符串中找到正則表達式所匹配的所有子串,但是把它們作為一個迭代器返回。語法格式如下:
In [10]: re.finditer?
Signature: re.finditer(pattern, string, flags=0)
Docstring:
Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a Match object.Empty matches are included in the result.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示匹配的正則表達式。
2.string: 表示要匹配的字符串。
3.flags: 表示標志位,用戶控制正則表達式的匹配方式,如是否區分大小寫、多行匹配等。
4.返回值: 返回一個符合表達式匹配結果的迭代器。
示例:獲取字符串中的數字。使用finditer()方法獲取字符串中的所有數值,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊# 獲取字符串中的數字
it = re.finditer(r"\d+", "12a32bc43jf3")
# 便利獲取后的迭代對象
for match in it:print(type(match), match) # <class 're.Match'> <re.Match object; span=(3, 5), match='32'>print(match.group()) # 打印數字 12 32 43 3
3.5 fullmatch()方法——對整個字符串進行匹配
fullmatch() 方法用于對整個字符串進行匹配,如果整個字符串匹配到正則表達式樣式,就返回一個相應的匹配對象,否則就返回一個 None。語法格式如下:
In [11]: re.fullmatch?
Signature: re.fullmatch(pattern, string, flags=0)
Docstring:
Try to apply the pattern to all of the string, returning
a Match object, or None if no match was found.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示模式字符串,由要匹配的正則表達式轉換而來。
2.string: 表示要匹配的字符串。
3.flags: 可選參數,表示標志位,用于控制匹配方式,如是否區分字母大小寫。
4.返回值: 如果整個 string 匹配到正則表達式樣式,就返回一個相應的 Match 對象。
示例:匹配整個字符串。使用fullmatch()方法實現匹配整個字符串,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊string1 = "mr00soft" # 需要匹配的字符串
# 匹配包括下劃線在內的任何字符,并匹配前面的子表達式一次或多次
match1 = re.fullmatch('\w+', string1)
# 單個字符匹配任意次,貪婪匹配
match2 = re.fullmatch('.*', string1)
# 匹配多個數字
match3 = re.fullmatch('\d+', string1)
print(match1) # <re.Match object; span=(0, 8), match='mr00soft'>
print(match2) # <re.Match object; span=(0, 8), match='mr00soft'>
print(match3) # None
3.6 match()方法——從字符開始處進行匹配
match() 方法用于從字符串的開始處進行匹配,如果在起始位置匹配成功,則返回 Match 對象,否則返回 None。語法格式如下:
In [12]: re.match?
Signature: re.match(pattern, string, flags=0)
Docstring:
Try to apply the pattern at the start of the string, returning
a Match object, or None if no match was found.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示模式字符串,由要匹配的正則表達式轉換而來。
2.string: 表示要匹配的字符串。
3.flags: 可選參數,表示標志位,用于控制匹配方式,如是否區分字母大小寫。
4.返回值: 如果 string 的開始處有 0 或多個字符匹配到了正則表達式樣式,就返回一個相應的Match 對象。
示例:判斷匹配字符串是否以“mr_”開頭。使用match()方法判斷匹配字符串是否以“mr_”開頭,不區分字母大小寫,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = r'mr_\w+' # 模式字符串
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string, re.I) # 匹配字符串,不區分大小寫
print(match) # 打印匹配結果 <re.Match object; span=(0, 7), match='MR_SHOP'>
string = '項目名稱MR_SHOP mr_shop'
match = re.match(pattern, string, re.I) # 匹配字符串,不區分大小寫
print(match) # 打印匹配結果 None
3.7 search()方法——搜索第一個匹配位置
search() 方法用于在整個字符串中搜索第一個匹配的值,如果匹配成功,則返回 Match 對象,否則返回 None。語法格式如下:
In [13]: re.search?
Signature: re.search(pattern, string, flags=0)
Docstring:
Scan through string looking for a match to the pattern, returning
a Match object, or None if no match was found.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示模式字符串,由要匹配的正則表達式轉換而來。
2.string: 表示要匹配的字符串。
3.flags: 可選參數,表示標志位,用于控制匹配方式,如是否區分字母大小寫。
4.返回值: 掃描整個字符串找到匹配樣式的第一個位置,并返回一個相應的匹配對象。如果沒有匹配,就返回一個 None。
注意,這和找到一個零長度匹配是不同的。
示例:搜索第一個以“mr_”開頭的字符串,使用search()方法搜索第一個以“mr_”開頭的字符串,不區分字母大小寫,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = r'mr_\w+' # 模式字符串
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.search(pattern, string, re.I) # 搜索字符串,不區分大小寫
print(match) # 打印匹配結果 <re.Match object; span=(0, 7), match='MR_SHOP'>
string = '項目名稱MR_SHOP mr_shop'
match = re.search(pattern, string, re.I) # 搜索字符串,不區分大小寫
print(match) # 打印匹配結果 <re.Match object; span=(4, 11), match='MR_SHOP'>
3.8 split()方法——根據正則表達式分割字符串
split() 方法用于實現根據正則表達式分割字符串,并以列表的形式返回。其作用同字符串對象的 split() 方法類似,所不同的就是分割字符由模式字符串指定。語法格式如下:
In [14]: re.split?
Signature: re.split(pattern, string, maxsplit=0, flags=0)
Docstring:
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings. If
capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list. If maxsplit is nonzero, at most maxsplit splits occur,
and the remainder of the string is returned as the final element
of the list.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示模式字符串,由要匹配的正則表達式轉換而來。
2.string: 表示要匹配的字符串。
3.maxsplit: 可選參數,表示最大的拆分次數。
4.flags: 可選參數,表示標志位,用于控制匹配方式,如是否區分字母大小寫。
5.返回值: 返回一個分割后的字符串列表。
示例:從給定的 URL 地址中提取出請求地址和各個參數。使用split()方法實現從給定的URL地址中提取出請求地址和各個參數的功能,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = r'[?|&]' # 定義分割符
url = 'http://www.mingrisoft.com/login.jsp?username="mr"&pwd="mrsoft"'
result = re.split(pattern, url) # 分割字符串
print(result) # ['http://www.mingrisoft.com/login.jsp', 'username="mr"', 'pwd="mrsoft"']
3.9 sub()方法——字符串替換
sub() 方法用于實現字符串替換。語法格式如下:
In [15]: re.sub?
Signature: re.sub(pattern, repl, string, count=0, flags=0)
Docstring:
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the Match object and must return
a replacement string to be used.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示模式字符串,由要匹配的正則表達式轉換而來。
2.repl: 表示替換的字符串。
3.string: 表示要被查找替換的原始字符串。
4.count: 可選參數,表示模式匹配后替換的最大次數,默認值為 0,表示替換所有的匹配。
5.flags: 可選參數,表示標志位,用于控制匹配方式,如是否區分字母大小寫。
6.返回值: 返回替換后的字符串。
示例1:隱藏中獎信息中的手機號碼。使用sub()方法實現隱藏中獎信息中的手機號碼的功能,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = r'1[34578]\d{9}' # 定義要替換的模式字符串
string = '中獎號碼為:84978981 聯系電話為:13611111111'
result = re.sub(pattern, '1XXXXXXXXXX', string) # 替換字符串
print(result) # 中獎號碼為:84978981 聯系電話為:1XXXXXXXXXX
示例2:排除字符串中的漢字、字母與數字。使用sub()方法排除字符串中的漢字、字母與數字,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re# 定義需要篩選的字符串
string = 'abcdefghijklmnopqrstuvwxyz我愛Python0123456789!#$%&*+-.^_`|~'
result = re.sub("[A-Za-z0-9\u4e00-\u9fa5]", "", string) # 替換字符串
print(result) # 打印替換結果 !#$%&*+-.^_`|~
3.10 subn()方法——字符串替換 (含替換次數)
subn() 方法與 sub() 方法相同,都是用于實現字符串的替換。但 subn() 方法返回一個元組,其中包含新字符串和替換次數。語法格式如下:
In [16]: re.subn?
Signature: re.subn(pattern, repl, string, count=0, flags=0)
Docstring:
Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the Match object and must
return a replacement string to be used.
File: f:\dev_tools\python\python310\lib\re.py
Type: function參數說明:
1.pattern: 表示模式字符串,由要匹配的正則表達式轉換而來。
2.repl: 表示替換的字符串。
3.string: 表示要被查找替換的原始字符串。
4.count: 可選參數,表示模式匹配后替換的最大次數,默認值為 0,表示替換所有的匹配。
5.flags: 可選參數,表示標志位,用于控制匹配方式,如是否區分字母大小寫。
6.返回值: 返回一個包含替換后字符串與替換次數的元組。
示例:替換字符串中的指定內容。使用subn()方法實現替換字符串中的指定內容的功能,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊# ('AA3456abcdef', 2)
print(re.subn('[1-2]', 'A', '123456abcdef')) # 打印元組,包含新字符串與替換次數
# I have A, I have B ,I have C
print(re.sub('g.t', 'have', 'I get A, I got B ,I gut C')) # 打印新字符串
# ('I have A, I have B ,I have C', 3)
print(re.subn('g.t', 'have', 'I get A, I got B ,I gut C')) # 打印元組,包含新字符串與替換次數
3.11 Pattern的屬性以及方法
3.11.1 Pattern.flags屬性——獲取正則匹配標記
Pattern.flags 屬性用于獲取正則表達式中匹配模式對應的標記。語法格式如下:
Pattern.flags
示例:獲取常見匹配模式對應的標記。使用Pattern.flags屬性獲取常見匹配模式對應的標記,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern_I = re.compile('\w+', flags=re.I) # 匹配模式,忽略大小寫
pattern_M = re.compile('\w+', flags=re.M) # 匹配模式,多行
pattern_S = re.compile('\w+', flags=re.S) # 匹配模式,使用"."字符匹配所有字符,包括換行符
pattern_X = re.compile('\w+', flags=re.X) # 匹配模式,忽略模式字符串中未轉義的空格和注釋
print('匹配模式I的標記為:', pattern_I.flags)
print('匹配模式M的標記為:', pattern_M.flags)
print('匹配模式S的標記為:', pattern_S.flags)
print('匹配模式X的標記為:', pattern_X.flags)
3.11.2 Pattern.groups屬性——捕獲組合的數量
Pattern.groups 屬性用于獲取正則表達式中組合的數量。語法格式如下:
Pattern.groups
示例: 獲取正則表達式中組合的數量。使用Pattern.groups屬性獲取正則表達式中組合的數量,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(\w+) (\w+)') # 組合表達式
print('組合數量為:', pattern.groups)
3.11.3 Pattern.groupindex屬性——獲取分組名稱與對應的分組編號
Pattern.groupindex 屬性用于獲取正則表達式中分組名稱與對應的分組編號。語法格式如下:
Pattern.groupindex
示例:獲取表達式中分組名稱與對應的分組編號。使用Pattern.groupindex屬性獲取表達式中分組名稱與對應的分組編號,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)') # 分組表達式
# 分組名稱與對應的編號為: {'group_1': 1, 'group_2': 2}
print('分組名稱與對應的編號為:', pattern.groupindex)
3.11.4 Pattern.pattern屬性——獲取模式字符串
Pattern.pattern 屬性用于獲取正則表達式中的模式字符串。語法格式如下:
Pattern.pattern
示例:獲取表達式中的模式字符串。使用Pattern.pattern屬性獲取表達式中的模式字符串,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)') # 分組表達式
print(pattern.pattern) # (?P<group_1>\w+) (?P<group_2>\w+)
3.11.5 Pattern.f?indall()方法——搜索所有符合正則表達式的字符串
Pattern.findall() 方法用于在整個字符串中搜索所有符合正則表達式的字符串,并以列表的形式返回。如果匹配成功,則返回包含匹配結構的列表,否則返回空列表。該方法可以指定匹配字符串的范圍。語法格式如下:
In [21]: pattern.findall?
Signature: pattern.findall(string, pos=0, endpos=9223372036854775807)
Docstring: Return a list of all non-overlapping matches of pattern in string.
Type: builtin_function_or_method參數說明:
1.string: 表示需要匹配的字符串。
2.pos: 表示匹配的起始位置,該參數為可選參數,默認值為 0。
3.endpos: 表示匹配的結束位置,該參數為可選參數,默認為需要匹配字符串的長度,所以只有從 pos 到 endpos-1 的字符會被匹配。
4.返回值: 返回一個符合表達式匹配結果的列表。
示例:搜索字符串中以“mr_”開頭的字符串。使用Pattern.findall()方法搜索字符串中以“mr_”開頭的字符串,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('mr_\w+') # 正則表達式對象
string = 'mr_SHOP mr_shop' # 要匹配的字符串
match = pattern.findall(string) # 搜索字符串
print(match) # 打印匹配結果 ['mr_SHOP', 'mr_shop']
print(pattern.findall(string, 0, 5)) # 打印下標0~5的結果 ['mr_SH']
3.11.6 Pattern.f?inditer()方法——搜索所匹配的所有子串
Pattern.finditer() 方法用于在字符串中找到正則表達式所匹配的所有子串,把它們作為一個迭代器返回。該方法可以指定匹配字符串的范圍。語法格式如下:
In [28]: pattern.finditer?
Signature: pattern.finditer(string, pos=0, endpos=9223372036854775807)
Docstring:
Return an iterator over all non-overlapping matches for the RE pattern in string.For each match, the iterator returns a match object.
Type: builtin_method參數說明:
1.string: 表示需要匹配的字符串。
2.pos: 表示匹配的起始位置,該參數為可選參數,默認值為 0。
3.endpos: 表示匹配的結束位置,該參數為可選參數,默認為需要匹配字符串的長度,所以只有從 pos 到 endpos-1 的字符會被匹配。
4.返回值: 返回一個符合表達式匹配結果的迭代器。
示例:獲取字符串中指定范圍的所有數字。使用Pattern.finditer()方法獲取字符串中指定范圍的所有數字,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('\d+') # 正則表達式對象
string = '12a32bc43jf3' # 要匹配的字符串
it = pattern.finditer(string, 2, 8)
# 遍歷獲取后的迭代對象
for match in it:print(match.group()) # 打印數字
3.11.7 Pattern.fullmatch()方法——對整個字符串匹配
Pattern.fullmatch() 方法用于對整個字符串匹配。從 pos 下標位置開始逐個對字符串進行匹配直到 endpos 下標位置,如果匹配成功則返回匹配成功的 Match 對象;如果沒有匹配成功,就返回None。語法格式如下:
In [27]: pattern.fullmatch?
Signature: pattern.fullmatch(string, pos=0, endpos=9223372036854775807)
Docstring: Matches against all of the string.
Type: builtin_method參數說明:
1.string: 表示需要匹配的字符串。
2.pos: 表示匹配的起始位置,該參數為可選參數,默認值為 0。
3.endpos: 表示匹配的結束位置,該參數為可選參數,默認為需要匹配字符串的長度,所以只有從 pos 到 endpos-1 的字符會被匹配。
4.返回值: 如果整個 string 匹配到正則表達式樣式,就返回一個相應的 Match 對象。
示例:獲取字符串中開始處符合表達式的值。使用Pattern.fullmatch()方法獲取字符串中開始處符合表達式的值,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('[a-z]+') # 定義匹配字母的表達式
string = 'abcskd123jaw123' # 需要匹配的字符串
print(pattern.fullmatch(string, 0, 5)) # 打印匹配結果,匹配范圍0~5
3.11.8 Pattern.match()方法——從字符開始處匹配字符串的值
Pattern.match() 方法用于從字符開始處匹配字符串的值,從 pos 下標位置開始逐個對字符串進行匹配直到 endpos 下標位置,如果匹配成功則返回匹配成功的 Match 對象;如果沒有匹配成功,就返回 None。語法格式如下:
In [26]: pattern.match?
Signature: pattern.match(string, pos=0, endpos=9223372036854775807)
Docstring: Matches zero or more characters at the beginning of the string.
Type: builtin_method參數說明:
1.string: 表示需要匹配的字符串。
2.pos: 表示匹配的起始位置,該參數為可選參數,默認值為 0。
3.endpos: 表示匹配的結束位置,該參數為可選參數,默認為需要匹配字符串的長度,所以只有從 pos 到 endpos-1 的字符會被匹配。
4.返回值: 如果 string 開始的位置可以匹配到正則表達式樣式,就返回一個相應的 Match 對象。
示例:獲取字符串中開始處符合表達式的值。使用Pattern.match()方法獲取字符串中開始處符合表達式的值,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('[a-z]+') # 定義匹配字母的表達式
string = '12312abc1234546lskdj' # 需要匹配的字符串
# <re.Match object; span=(5, 8), match='abc'>
print(pattern.match(string, 5, 10)) # 打印匹配結果,匹配范圍5~10
3.11.9 Pattern.search()方法——搜索第一個匹配的位置
Pattern.search() 方法用于搜索第一個匹配的位置,從 pos 下標位置開始逐個對字符串進行匹配直到 endpos 下標位置,如果匹配成功,則返回匹配成功的 Match 對象,否則返回 None。語法格式如下:
In [25]: pattern.search?
Signature: pattern.search(string, pos=0, endpos=9223372036854775807)
Docstring:
Scan through string looking for a match, and return a corresponding match object instance.Return None if no position in the string matches.
Type: builtin_method參數說明:
1.string: 表示需要匹配的字符串。
2.pos: 表示匹配的起始位置,該參數為可選參數,默認值為 0。
3.endpos: 表示匹配的結束位置,該參數為可選參數,默認為需要匹配字符串的長度,所以只有從 pos 到 endpos-1 的字符會被匹配。
4.返回值: 掃描整個字符串找到匹配樣式的第一個位置,并返回一個相應的匹配對象。
示例:獲取字符串中第一個匹配值與位置。使用Pattern.search()方法獲取字符串中第一個匹配值與位置,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('[0-9]+') # 定義匹配數字的表達式
string = '12312abc1234546lskdj' # 需要匹配的字符串
print(pattern.search(string, 0, 10)) # 打印匹配結果,匹配范圍0~10
3.11.10 Pattern.split()方法——同split()方法
Pattern.split() 方法與 re.split() 方法相同,用于實現根據正則表達式分割字符串,并以列表的形式返回。其作用同字符串對象的 split() 方法類似,所不同的是分割字符由模式字符串指定。語法格式如下:
In [24]: pattern.split?
Signature: pattern.split(string, maxsplit=0)
Docstring: Split string by the occurrences of pattern.
Type: builtin_function_or_method參數說明:
1.string: 表示需要匹配的字符串。
2.maxsplit: 可選參數,表示最大的拆分次數。
3.返回值: 返回一個分割后的字符串列表。
示例:從給定的 URL 地址中提取出請求地址和各個參數。使用Pattern.split()方法實現從給定的URL地址中提取出請求地址和各個參數,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('[?|&]') # 定義分割符url = 'http://www.mingrisoft.com/login.jsp?username="mr"&pwd="mrsoft"'
# ['http://www.mingrisoft.com/login.jsp', 'username="mr"', 'pwd="mrsoft"']
result = pattern.split(url) # 分割字符串
print(result)
3.11.11 Pattern.sub()方法——字符串替換
Pattern.sub() 方法與 re.sub() 方法相同,用于實現字符串替換。語法格式如下:
In [23]: pattern.sub?
Signature: pattern.sub(repl, string, count=0)
Docstring: Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl.
Type: builtin_method參數說明:
1.repl: 表示替換的字符串。
2.string: 表示要被查找替換的原始字符串。
3.count: 可選參數,表示模式匹配后替換的最大次數,默認值為 0,表示替換所有的匹配。
4.返回值: 返回替換后的字符串。
示例:隱藏中獎信息中的手機號碼。使用Pattern.sub()方法實現隱藏中獎信息中的手機號碼的功能,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('1[34578]\d{9}') # 定義要替換的模式字符串
string = '中獎號碼為:84978981 聯系電話為:13611111111'
result = pattern.sub('1XXXXXXXXXX', string) # 替換字符串
print(result) # 中獎號碼為:84978981 聯系電話為:1XXXXXXXXXX
3.11.12 Pattern.subn()方法——字符串替換(含替換次數)
Pattern.subn() 方法與 re.subn() 方法相同,都是用于實現字符串的替換并返回一個元組,其中包含新字符串和替換次數。語法格式如下:
In [22]: pattern.subn?
Signature: pattern.subn(repl, string, count=0)
Docstring: Return the tuple (new_string, number_of_subs_made) found by replacing the leftmost
non-overlapping occurrences of pattern with the replacement repl.
Type: builtin_method參數說明:
1.repl: 表示替換的字符串。
2.string: 表示要被查找替換的原始字符串。
3.count: 可選參數,表示模式匹配后替換的最大次數,默認值為 0,表示替換所有的匹配。
4.返回值: 返回一個包含替換后字符串與替換次數的元組。
示例:替換字符串中的指定內容。使用Pattern.subn()方法實現替換字符串中的指定內容的功能,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('[1-2]') # 數值替換表達式,替換字符串中的1-2
pattern2 = re.compile('g.t') # 字幕替換表達式,替換字符串中的get、got、gut
# 需要匹配的字符串
string = '123456abcdef'
string2 = 'I get A, I got B ,I gut C'
print(pattern.subn('A', string)) # 打印元組,包含新字符串與替換次數 ('AA3456abcdef', 2)
print(pattern2.sub('have', string2)) # 打印新字符串 I have A, I have B ,I have C
print(pattern2.subn('have', string2)) # 打印元組,包含新字符串與替換次數 ('I have A, I have B ,I have C', 3)
3.12 Match對象屬性及方法
3.12.1 Match.endpos屬性——結束匹配的索引位置
Match.endpos 屬性用于獲取正則表達式在字符串結束匹配的索引位置。語法格式如下:
Match.endpos
示例:獲取正則表達式在字符串結束匹配的索引位置。使用Match.endpos屬性獲取正則表達式在字符串結束匹配的索引位置,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('mr_\w+') # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.search(pattern, string) # 匹配結果Match對象
print(match) # 打印匹配的Match對象 <re.Match object; span=(8, 15), match='mr_shop'>
print(match.endpos) # 打印匹配的結束位置 15
3.12.2 Match.pos屬性——開始匹配的索引位置
Match.pos 屬性用于獲取正則表達式在字符串開始匹配的索引位置。語法格式如下:
Match.pos
示例:獲取正則表達式在字符串開始匹配的索引位置。使用Match.pos屬性獲取正則表達式在字符串開始匹配的索引位置,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('mr_\w+') # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.search(pattern, string) # 匹配結果Match對象
print(match) # 打印匹配的Match對象
print(match.pos) # 打印匹配的起始位置
3.12.3 Match.lastindex屬性——捕獲組的最后一個匹配的索引值
Match.lastindex 屬性用于捕獲組的最后一個匹配的索引值。語法格式如下:
Match.lastindex
示例:獲取最后一個匹配到的組所對應的索引值。使用Match.lastindex屬性獲取最后一個匹配到的組所對應的索引值,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.lastindex) # 打印最后一個匹配到的組所對應的索引值 2
3.12.4 Match.lastgroup屬性——獲取最后一個匹配組的名稱
Match.lastgroup 屬性用于獲取最后一個匹配組的名稱,如果匹配的組沒有名字或者沒有產生匹配的情況下,則返回 None。語法格式如下:
In [44]: match.lastgroup?
Type: NoneType
String form: None
Docstring: <no docstring>
示例:獲取最后一個匹配組的名稱。使用Match.lastgroup屬性獲取最后一個匹配組的名稱,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.lastgroup) # 打印最后一個匹配組的名稱
3.12.5 Match.re屬性——返回正則表達式對象
Match.re 屬性用于獲取產生 Match 實例的正則表達式對象。語法格式如下:
In [43]: match.re?
Type: Pattern
String form: re.compile('\\d')
File: f:\dev_tools\python\python310\lib\re.py
Docstring: Compiled regular expression object.
示例:獲取產生Match實例的正則表達式對象。使用Match.re屬性獲取產生Match實例的正則表達式對象,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.re) # 打印獲取的表達式對象
3.12.6 Match.string屬性——獲取需要匹配的字符串
Match.string 屬性用于獲取 Match 對象中需要匹配的字符串。語法格式如下:
In [42]: match.string?
Type: str
String form: 123456
Length: 6
Docstring:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
示例:獲取Match對象中需要匹配的字符串。使用Match.string屬性獲取Match對象中需要匹配的字符串,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.string) # 打印Match對象中需要匹配的字符串 MR_SHOP mr_shop
3.12.7 Match.__getitem__()
方法——返回一個匹配的分組信息
Match.__getitem__()
方法與 Match.group() 方法相似,只是 __getitem__()
方法每次只能獲取一個分組的信息。語法格式如下:
In [41]: match.__getitem__?
Signature: match.__getitem__(key, /)
Call signature: match.__getitem__(*args, **kwargs)
Type: method-wrapper
String form: <method-wrapper '__getitem__' of re.Match object at 0x000001BEA4520240>
Docstring: Return self[key].參數說明:
1.g: 表示分組對應的編號或分組名稱。
2.返回值: 返回一個匹配的分組信息。
示例:獲取指定分組對應的信息。使用Match.__getitem__()
方法獲取指定分組對應的信息,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.__getitem__(1)) # 打印指定分組編號對應內容 MR_SHOP
print(match.__getitem__('group_2')) # 打印指定分組名對應內容mr_shop
3.12.8 Match.end()方法——返回分組匹配字符串對應的結束標記
Match.end() 方法用于獲取分組匹配字符串對應的結束標記。語法格式如下:
In [40]: match.end?
Signature: match.end(group=0, /)
Docstring: Return index of the end of the substring matched by group.
Type: builtin_function_or_method參數說明:
1.group: 表示分組名或者分組名對應的編號。
2.返回值: 返回分組匹配字符串對應的結束標記。
示例:獲取分組匹配字符串對應的開始、結束標記。使用Match.start()方法與Match.end()方法獲取分組匹配字符串對應的開始、結束標記,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.start(), match.end()) # 打印全部分組的匹配字符串對應的開始、結束標記 0 15
print(match.start(1), match.end(1)) # 打印編號1分組的匹配字符串對應的開始、結束標記 0 7
print(match.start(2), match.end(2)) # 打印編號2分組的匹配字符串對應的開始、結束標記 8 15
# 打印分組名的匹配字符串對應的開始、結束標記
print(match.start('group_1'), match.end('group_2')) # 0 15
3.12.9 Match.expand()方法——對“\”進行轉義替換并返回
Match.expand() 方法用于實現把字符串中用反斜杠 "\"
表示的數字或組名替換為相應分組中的值的功能。語法格式如下:
In [39]: match.expand?
Signature: match.expand(template)
Docstring: Return the string obtained by doing backslash substitution on the string template,
as done by the sub() method.
Type: builtin_function_or_method參數說明:
1.template: 表示需要替換的字符串。
2.返回值: 返回對"\"進行轉義替換的結果。
示例:在字符串中指定位置替換對應分組中的值。使用Match.expand()方法,在字符串中指定位置替換對應分組中的值,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match[1]) # 打印分組1內容 MR_SHOP
print(match[2]) # 打印分組2內容 mr_shop
# 第一種替換方式,\1、\2替換分組1和2的內容
print(match.expand(r'first_ \1 \2')) # first_ MR_SHOP mr_shop
# 第二種替換方式,\g<1>、\g<2>替換分組1和2的內容
print(match.expand('second_ \g<1> \g<2>')) # second_ MR_SHOP mr_shop
# 第三種替換方式,\g<group_1>、\g<group_2>替換分組1和2的內容
print(match.expand('third_ \g<group_1> \g<group_2>')) # third_ MR_SHOP mr_shop
3.12.10 Match.groups()方法——以元組形式返回所有子組中內容
Match.groups() 方法用于獲取以元組形式返回所有子組中內容。語法格式如下:
In [38]: match.groups?
Signature: match.groups(default=None)
Docstring:
Return a tuple containing all the subgroups of the match, from 1.defaultIs used for groups that did not participate in the match.
Type: builtin_function_or_method參數說明:
1.default: 用于不參與匹配的情況,默認為 None。
2.返回值: 以元組形式返回所有子組中內容。
示例:獲取所有分組對應的內容。使用Match.groups()方法獲取所有分組對應的內容,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.groups()) # 打印所有分組對應的內容 ('MR_SHOP', 'mr_shop')
3.12.11 Match.group()方法——返回一個或者多個匹配的子組
Match.group() 方法用于獲取 Match 對象中一個或多個匹配的子組。如果只有一個(0~99)參數,結果就是一個字符串;如果有多個參數,結果就是一個元組(每個參數對應一個項);如果沒有參數,組 1 默認到 0(整個匹配都被返回)。如果一個組 N 參數值為 0,相應的返回值就是整個匹配字符串;如果一個組號是負數或超出組的最大長度,則給出越界錯誤;如果正則表達式中的一個組匹配了多個值,則相應的組只保存最后匹配的值。語法格式如下:
In [37]: match.group?
Docstring:
group([group1, ...]) -> str or tuple.
Return subgroup(s) of the match by indices or names.
For 0 returns the entire match.
Type: builtin_function_or_method參數說明:
1.group1: 表示分組對應的編號或分組名稱。
2.返回值: 返回一個或者多個匹配的子組。
示例:獲取指定分組對應的信息。使用Match.group()方法獲取指定分組對應的信息,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.group()) # 無參數打印全部內容 MR_SHOP mr_shop
print(match.group(1)) # 打印指定分組編號對應內容 MR_SHOP
print(match.group('group_2')) # 打印指定分組名對應內容 mr_shop
3.12.12 Match.groupdict()方法——返回包含所有匹配值分組的字典
Match.groupdict() 方法用于獲取以字典形式返回包含所有匹配值分組的信息,其中 key 就是組名,value 就是分組匹配的信息內容。語法格式如下:
In [36]: match.groupdict?
Signature: match.groupdict(default=None)
Docstring:
Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name.defaultIs used for groups that did not participate in the match.
Type: builtin_function_or_method參數說明:
1.default: 用于不參與匹配的情況,默認為 None。
2.返回值: 以字典形式返回包含所有匹配值分組的信息。
示例:獲取字典形式的分組信息。使用Match.groupdict()方法獲取字典形式的分組信息,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
# {'group_1': 'MR_SHOP', 'group_2': 'mr_shop'}
print(match.groupdict()) # 打印字典形式的分組信息
3.12.13 Match.span()方法——返回包含開始和結束位置的二元組
Match.span() 方法用于獲取指定分組匹配字符串的開始和結束位置。語法格式如下:
In [35]: match.span?
Signature: match.span(group=0, /)
Docstring: For match object m, return the 2-tuple (m.start(group), m.end(group)).
Type: builtin_function_or_method參數說明:
1.group: 表示分組名或者分組名對應的編號。
2.返回值: 返回一個包含開始和結束位置的二元組。
示例:獲取指定分組匹配字符串的開始和結束位置。使用Match.span()方法獲取指定分組匹配字符串的開始和結束位置,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.span(1)) # 打印分組編號1匹配字符串對應的開始、結束標記 (0, 7)
print(match.span('group_2')) # 打印分組名group_2匹配字符串對應的開始、結束標記 (8, 15)
3.12.14 Match.start()方法——返回分組匹配字符串對應的開始標記
Match.start() 方法用于獲取分組匹配字符串對應的開始標記。語法格式如下:
In [34]: match.start?
Signature: match.start(group=0, /)
Docstring: Return index of the start of the substring matched by group.
Type: builtin_function_or_method參數說明:
1.group: 表示分組名或者分組名對應的編號。
2.返回值: 返回分組匹配字符串對應的開始標記。
示例1:獲取分組匹配字符串對應的開始、結束標記。使用Match.start()方法與Match.end()方法獲取分組匹配字符串對應的開始、結束標記,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.match(pattern, string) # 匹配結果Match對象
print(match.start(), match.end()) # 打印全部分組的匹配字符串對應的開始、結束標記 0 15
print(match.start(1), match.end(1)) # 打印編號1分組的匹配字符串對應的開始、結束標記 0 7
print(match.start(2), match.end(2)) # 打印編號2分組的匹配字符串對應的開始、結束標記 8 15
# 打印分組名的匹配字符串對應的開始、結束標記
print(match.start('group_1'), match.end('group_2')) # 0 15
示例2:移除表達式搜索的內容。通過Match.start()方法與Match.end()方法移除指定內容,代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2024-09-25 9:50
# @Author : AmoXiang
# @File: re_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680import re # 導入正則表達式re模塊pattern = re.compile('(?P<group_1>\w+) (?P<group_2>\w+)', re.I) # 分組表達式
string = 'MR_SHOP mr_shop' # 要匹配的字符串
match = re.search('SHOP mr_', string) # 匹配結果Match對象
print(string) # 打印原字符串 MR_SHOP mr_shop
print(match) # 打印需要移除的內容 <re.Match object; span=(3, 11), match='SHOP mr_'>
print(string[:match.start()] + string[match.end():]) # 打印移除后的內容 MR_shop
四、練習
《Python練習寶典:Day 3 - 選擇題 - 字符串與正則表達式、基礎練習補充》 👉 查看文章 參考 二、字符串與正則表達式 一節。
至此今天的學習就到此結束了,筆者在這里聲明,筆者寫文章只是為了學習交流,以及讓更多學習Python語言的讀者少走一些彎路,節省時間,并不用做其他用途,如有侵權,聯系博主刪除即可。感謝您閱讀本篇博文,希望本文能成為您編程路上的領航者。祝您閱讀愉快!
????好書不厭讀百回,熟讀課思子自知。而我想要成為全場最靚的仔,就必須堅持通過學習來獲取更多知識,用知識改變命運,用博客見證成長,用行動證明我在努力。
????如果我的博客對你有幫助、如果你喜歡我的博客內容,請點贊
、評論
、收藏
一鍵三連哦!聽說點贊的人運氣不會太差,每一天都會元氣滿滿呦!如果實在要白嫖的話,那祝你開心每一天,歡迎常來我博客看看。
?編碼不易,大家的支持就是我堅持下去的動力。點贊后不要忘了關注
我哦!