python正則表達式模塊簡介
Python 自1.5版本起增加了re 模塊,它提供 Perl 風格的正則表達式模式。Python 1.5之前版本則是通過 regex 模塊提供 Emacs 風格的模式。Emacs 風格模式可讀性稍差些,而且功能也不強,因此編寫新代碼時盡量不要再使用 regex 模塊,當然偶爾你還是可能在老代碼里發現其蹤影。
就其本質而言,正則表達式(或 RE)是一種小型的、高度專業化的編程語言,(在Python中)它內嵌在Python中,并通過 re 模塊實現。使用這個小型語言,你可以為想要匹配的相應字符串集指定規則;該字符串集可能包含英文語句、e-mail地址、TeX命令或任何你想搞定的東西。然后你可以問諸如“這個字符串匹配該模式嗎?”或“在這個字符串中是否有部分匹配該模式呢?”。你也可以使用 RE 以各種方式來修改或分割字符串。
正則表達式模式被編譯成一系列的字節碼,然后由用 C 編寫的匹配引擎執行。在高級用法中,也許還要仔細留意引擎是如何執行給定 RE ,如何以特定方式編寫 RE 以令生產的字節碼運行速度更快。本文并不涉及優化,因為那要求你已充分掌握了匹配引擎的內部機制。
正則表達式語言相對小型和受限(功能有限),因此并非所有字符串處理都能用正則表達式完成。當然也有些任務可以用正則表達式完成,不過最終表達式會變得異常復雜。碰到這些情形時,編寫 Python 代碼進行處理可能反而更好;盡管 Python 代碼比一個精巧的正則表達式要慢些,但它更易理解。
正則表達式一個比較常見的用途是找到所有模式匹配的字符串并用不同的字符串來替換它們。sub方法提供一個替換值,可以是字符串或函數,和一個要被處理的字符串。
Grammar:
1
|
re.sub(pattern, repl, string[, count]) |
使用repl替換string中每一個匹配的子串后返回替換后的字符串。
當repl是一個字符串時,可以使用\id或\g、\g引用分組,但不能使用編號0。
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),并返回一個字符串用于替換(返回的字符串中不能再引用分組)。
count用于指定最多替換次數,不指定時全部替換。
1
|
re.subn(pattern, repl, string[, count]) |
返回 (sub(repl, string[, count]), 替換次數)。
Case:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#coding=utf-8 import re str = "https://i.cnb1logs.co2m/Edi3tPosts.asp4x?opt=999" pattern = re. compile (r '(\.)' ) print '\. :' ,re.sub(pattern, '-' , str ) pattern = re. compile (r '\/([^*]+)\/' ) print '\/([^*]+)\/ :' ,re.sub(pattern,r '<em>\1<em>' , str ) pattern = re. compile (r '(\w+)(\w+)(\d+)' ) #先切片測試 print re.split(pattern, str ) print re.sub(pattern,r '\3 \1' , str ) #subn統計sub替換次數 print re.subn(pattern,r '\3 \1' , str ) |
Output
1
2
3
4
5
6
|
\. : https: / / i - cnb1logs - co2m / Edi3tPosts - asp4x?opt = 999 \ / ([^ * ] + )\ / : https:<em> / i.cnb1logs.co2m<em>Edi3tPosts.asp4x?opt = 999 [ 'https://i.' , 'cn' , 'b' , '1' , 'logs.' , 'c' , 'o' , '2' , 'm/' , 'Ed' , 'i' , '3' , 'tPosts.' , 'as' , 'p' , '4' , 'x?opt=' , '9' , '9' , '9' , ''] https: / / i. 1 cnlogs. 2 cm / 3 EdtPosts. 4 asx?opt = 9 9 ( 'https://i.1 cnlogs.2 cm/3 EdtPosts.4 asx?opt=9 9' , 5 ) * * * Repl Closed * * * |
總結
原文鏈接:https://www.cnblogs.com/sub2020/p/7942113.html