網(wǎng)站首頁 編程語言 正文
一、re.sub(pattern, repl, string, count=0, flags=0)
re是正則的表達式,sub是substitute,表示替換
re.sub共有五個參數(shù)。
re.sub(pattern, repl, string, count=0, flags=0)
其中三個必選參數(shù):pattern, repl, string
兩個可選參數(shù):count, flags
二、參數(shù)講解
1、pattern參數(shù)
pattern
,表示正則中的模式字符串,這個沒太多要解釋的。
需要知道的是:
反斜杠加數(shù)字:\N
,則對應著匹配的組:matched group
比如\6
,表示匹配前面pattern
中的第6個group
意味著,pattern
中,前面肯定是存在對應的組,后面也才能去引用
舉個例子
hello xinfa, nihao xinfa
我們想把xinfa
替換成linxinfa
,就可以這樣:
import re inputStr = "hello xinfa, nihao xinfa" replacedStr = re.sub(r"hello (\w+), nihao \1", "linxinfa", inputStr) print("replacedStr = ", replacedStr) #輸出結果為: replacedStr = linxinfa
注意,上面的(\w+)
,括號括起來表示一個組;
里面的\w
表示匹配字母、數(shù)字、下劃線,等價于[A-Za-z0-9_]
;
然后+
表示匹配前面的子表達式一次或多次。
所以(\w+)
就是匹配多個字母、數(shù)字、下劃線的意思。表達式中的\1
表示匹配第一個組,第一個組就是(\w+)
。
2、repl參數(shù)
repl,就是replacement,被替換的字符串的意思。
repl可以是字符串,也可以是函數(shù)。
2.1、repl是字符串
如果repl
是字符串的話,其中的任何反斜杠轉(zhuǎn)義字符,都會被處理。
比如:
\n:會被處理為對應的換行符;
\r:會被處理為回車符;
其他不能識別的轉(zhuǎn)移字符,則只是被識別為普通的字符: 比如\j
,會被處理為j
這個字母本身;
比較特殊的是\g<n>
,\g
表示匹配組,n
是組的id
,比如\g<1>
表示第一個組。
還是上面的例子,我們想把xinfa
提取出來,只剩xinfa
hello xinfa, nihao xinfa
就可以這樣寫:
import re inputStr = "hello xinfa, nihao xinfa" replacedStr = re.sub(r"hello (\w+), nihao \1", "\g<1>", inputStr) print("replacedStr = ", replacedStr) #輸出結果為: replacedStr = xinfa
2.2、repl是函數(shù)
比如輸入內(nèi)容是:
hello 123 world 456
想要把其中的數(shù)字部分,都加上111,變成:
hello 234 world 567
那么就可以這樣:
#!/usr/bin/python # -*- coding: utf-8 -*- import re; def pythonReSubDemo(): """ demo Pyton re.sub """ inputStr = "hello 123 world 456" def _add111(matched): intStr = matched.group("number") intValue = int(intStr) addedValue = intValue + 111 addedValueStr = str(addedValue) return addedValueStr replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr) print("replacedStr=",replacedStr) #輸出結果為:replacedStr= hello 234 world 567 if __name__=="__main__": pythonReSubDemo()
注意上面,用了一個?P<value>
。
?P
的意思就是命名一個名字為value
的組,匹配規(guī)則符合后面的\d+
。
3、string參數(shù)
string
,即表示要被處理,要被替換的那個string
字符串。
4、count參數(shù)
舉例說明:
繼續(xù)之前的例子,假如對于匹配到的內(nèi)容,只處理其中一部分。
比如:
hello 123 world 456 nihao 789
我們只是想要處理前面兩個數(shù)字:123,456
,分別給他們加111
,而不處理789
,
那么就可以這樣:
#!/usr/bin/python # -*- coding: utf-8 -*- import re; def pythonReSubDemo(): """ demo Pyton re.sub """ inputStr = "hello 123 world 456 nihao 789" def _add111(matched): intStr = matched.group("number") intValue = int(intStr) addedValue = intValue + 111 addedValueStr = str(addedValue) return addedValueStr replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr, 2) print("replacedStr = ", replacedStr) #輸出結果為:replacedStr = hello 234 world 567 nihao 789 if __name__=="__main__": pythonReSubDemo()
5、flags參數(shù)
flags
是編譯標志。編譯標志讓你可以修改正則表達式的一些運行方式。
在re
模塊中標志可以使用兩個名字,一個是全名如IGNORECASE
,一個是縮寫,一字母形式如I
。(如果你熟悉 Perl 的模式修改,一字母形式使用同樣的字母;例如re.VERBOSE
的縮寫形式是re.X
。)
多個標志可以通過按位或
它們來指定。如re.I | re.M
被設置成I
和M
標志。
下面列舉下常用的編譯標志。
5.1、IGNORECASE(簡寫I)
使匹配對大小寫不敏感;
舉個例子,[A-Z]
也可以匹配小寫字母,Spam
可以匹配 Spam、spam
或spAM
。
5.2、LOCALE(簡寫L)
locales
是C
語言庫中的一項功能,是用來為需要考慮不同語言的編程提供幫助的。
舉個例子,如果你正在處理法文
文本,你想用 w+
來匹配文字,但w
只匹配字符類[A-Za-z]
,它并不能匹配é
。
如果你的系統(tǒng)配置適當且本地化設置為法語,那么內(nèi)部的 C
函數(shù)將告訴程序é
也應該被認為是一個字母。
當在編譯正則表達式時使用 LOCALE
標志會得到用這些 C
函數(shù)來處理 w
后的編譯對象,這會更慢,但也會象你希望的那樣可以用w+
來匹配法文
文本。
5.3、MULTILINE(簡寫M)
MULTILINE
多行的意思,改變 ^ 和 $ 的行為。
使用 ^
只匹配字符串的開始,而 $
則只匹配字符串的結尾和直接在換行前(如果有的話)的字符串結尾。
當本標志指定后,^
匹配字符串的開始和字符串中每行的開始。同樣的, $
元字符匹配字符串結尾和字符串中每行的結尾(直接在每個換行之前)。
例如
import re s='hello \nworld \nxinfa' print(s) pattern=re.compile(r'^\w+') print(re.findall(pattern,s)) #加上flags=re.M pattern=re.compile(r'^\w+', flags=re.M) print(re.findall(pattern,s))
輸出結果為
hello?
world?
xinfa
['hello']
['hello', 'world', 'xinfa']
5.4、DOTALL(簡寫S)
此模式下 .
的匹配不受限制,可匹配任何字符,包括換行符,也就是默認是不能匹配換行符。
例:
#!/usr/bin/python # -*- coding: utf-8 -*- import re s = '''first line ...: second line ...: third line''' regex=re.compile('.+') print(regex.findall(s)) regex=re.compile('.+', re.S) print(regex.findall(s))
輸出結:
['first line', ' ? ?...: second line', ' ? ?...: third line']
['first line\n ? ?...: second line\n ? ?...: third line']
5.5、VERBOSE(簡寫X)
冗余模式, 此模式忽略正則表達式中的空白和#號的注釋。
例:
email_regex = re.compile("[\w+\.]+@[a-zA-Z\d]+\.(com|cn)") email_regex = re.compile("""[\w+\.]+ # 匹配@符前的部分 @ # @符 [a-zA-Z\d]+ # 郵箱類別 \.(com|cn) # 郵箱后綴 """, re.X)
補充:repl為函數(shù)時的用法
當repl為函數(shù)時的替換更加靈活,此時可以在函數(shù)中自定義在某種特定的匹配下替換為某種特定的字符。
示例
import re # 將匹配的數(shù)字乘以 2 def double(matched): print('matched: ',matched) print("matched.group('value'): ",matched.group('value')) value = int(matched.group('value')) return str(value * 2) string = 'A23G4HFD567' print(re.sub('(?P<value>\d+)', double, string))
總結
原文鏈接:https://linxinfa.blog.csdn.net/article/details/93617615
相關推薦
- 2022-04-01 k8s Error: could not find tiller
- 2023-01-15 SqlServer?多種分頁方式?詳解(含簡單速度測試)_MsSql
- 2022-02-02 element ui el-dialog 居中,并且內(nèi)容多的時候內(nèi)部可以滾動
- 2023-06-19 python中time模塊指定格式時間字符串轉(zhuǎn)為時間戳_python
- 2022-09-08 Go語言中并發(fā)的工作原理_Golang
- 2022-10-23 Kubernetes?k8s?configmap?容器技術解析_云其它
- 2022-12-13 Kotlin?coroutineContext源碼層深入分析_Android
- 2023-10-16 elementUI日期選擇器快速選擇 快捷選擇(本周、上周、本月、上月、季度等)
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支