正規表示式 查詢,分割,替換

2021-10-05 12:57:12 字數 3424 閱讀 1078

**(1.1)查詢乙個匹配項:

**查詢並返回乙個匹配項的函式有3個:search,match,fullmatch。這3個函式的區別在於:

search:查詢任意位置的匹配項;

match:必須從字串開頭匹配;

fullmatch:整個字串與正則完全匹配

案例1:

import re

text=

'我愛你呀'

pattern=r'我愛你呀'

print

('search:'

,re.search(pattern,text)

)#search:查詢任意位置的匹配項

print

('match:'

,re.match(pattern,text)

)#match:必須從字串開頭匹配

print

('fullmatch:'

,re.fullmatch(pattern,text)

)#fullmatch:整個字串與正則完全匹配

執行結果為:列出text中與pattern匹配的項的初始位置(0),結束位置(5)和匹配項。

search:

; span=(0

,4), match=

'我愛你呀'

>

match:

; span=(0

,4), match=

'我愛你呀'

>

fullmatch:

; span=(0

,4), match=

'我愛你呀'

>

將上面的例子稍作改變,注意比較結果哦:

案例2:

import re

text=

'a我愛你呀'

pattern=r'我愛你呀'

print

('search:'

,re.search(pattern,text)

.group())

#通過補充「.group()」獲取匹配值。

print

('match:'

,re.match(pattern,text)

)print

('fullmatch:'

,re.fullmatch(pattern,text)

)

執行結果為:

search: 我愛你呀

match:

none

#text開頭加了個a,因此匹配失敗

fullmatch:

none

(1.2)查詢多個匹配項

查詢並返回多個匹配項的函式有2個:findall函式與finditer函式。這兩個函式的區別在於:

findall:從字串任意位置查詢,返回乙個列表。

finditer:從字串任意位置查詢,返回乙個迭代器。

案例3:

import re

text=

'a我愛你呀,我愛你呀'

pattern=r'我愛你呀'

print

('findall:'

,re.findall(pattern,text)

)print

('finditer:'

,list

(re.finditer(pattern,text)

))

結果為:

findall:

['我愛你呀'

,'我愛你呀'

]finditer:

[; span=(1

,5), match=

'我愛你呀'

>

,; span=(6

,10), match=

'我愛你呀'

>

]

語句:re.split(pattern, string, maxsplit=0, flags=0)

該函式中:用 pattern 分開 string , maxsplit表示最多進行分割次數, flags表示模式,就是上面我們講解的常量。

案例4:

text=

'a你說a,b我像雲捉摸不定b,c其實你不懂我的心'

pattern=r','

#正則分割

print

('split:'

,re.split(pattern,text,maxsplit=

1,flags=re.i)

)#逗號分割,分割1次,re.i不區分大小寫

執行結果為:

split:

['a你說a'

,'b我像雲捉摸不定b,c其實你不懂我的心'

]

替換主要有sub函式 與 subn函式,他們功能類似!

先來看看sub函式的用法:

re.sub(pattern, repl, string, count=0, flags=0)

函式引數講解:repl替換掉string中被pattern匹配的字元, count表示最大替換次數,flags表示正規表示式的常量。

值得注意的是:sub函式中的入參:repl替換內容既可以是字串,也可以是乙個函式哦! 如果repl為函式時,只能有乙個入參:match匹配物件。

先來看看subn函式的用法:

re.subn(pattern, repl, string, count=0, flags=0)

函式與 re.sub函式 功能一致,只不過返回乙個元組 (字串, 替換次數)。

案例5:

text=

'a你說a,b我像雲捉摸不定b,c其實你不懂我的心'

pattern=r','

repl=

'@'#repl為字串。用『@』替換『,』

print

('sub-repl為字串:'

,re.sub(pattern,repl,text,count=

1,flags=re.i)

)#該語句執行結果為:sub-repl為字串: a你說a@b我像雲捉摸不定b,c其實你不懂我的心

print

('subn-repl為字串:'

,re.subn(pattern,repl,text,count=

1,flags=re.i)

)#執行結果為:subn-repl為字串:('a你說a@b我像雲捉摸不定b,c其實你不懂我的心', 1)。可以看出結果為元組。

正規表示式 re常用方法 查詢 替換 分割

import re st wqew,safds,32,43.5454,fgewsa compile 用於編譯正規表示式,生成乙個正規表示式 pattern 物件 p re.compile r d print p.search st print re.search p,st sre.sre match...

xCode正規表示式替換查詢

self presentmodalviewcontroller imgpicker animated yes 在ios6已經deprecated,需要替換為其他格式 self presentviewcontroller imgpicker animated yes completion nil 如果...

正規表示式替換

正規表示式替換 每行的資料格式為 vcbi zuuu 001a465 kakid legos 要求變為格式為 vcbizuuu001 a465 kakid legos 替換掉第一部分和第二部分中間的空格,第二部分和第三部分中間的空格,其他的保持乙個空格 string originalstring v...