11.正則表達式(二)

目錄:
1.模塊介紹
2.單次匹配
3.全文搜索
4.匹配替換
5.分割字符串
6.分組

1.模塊介紹

Python使用re模塊提供了正則表達式處理的能力

       常量                        說明
re.M , re.MUITILINE              多行模式
re.S , re.DOTALL                 單行模式
re.I , re.IGNORECASE            忽略大小寫
re.X , re.VERBOSE               忽略表達式中的空白字符
# 使用 | 位或運算開啟多種選項

2.單次匹配

2.1 編譯
re.compile(pattern,flags=0),設(shè)定flags,編譯模式,返回正則表達式對象regex.pattern就是正則表達式字符串,flags是選項。正則表達式需要被
編譯,為了提高效率,這些編譯后的結(jié)果被保存,下次使用同樣的pattern的時候,就不需要再次編譯。re的其他方法為了提高效率都調(diào)用了編譯方法,
就是為了提速。
2.2 單詞匹配

1.match:

re.match(pattern,string,flags=0)
regex.match(string[,pos[,endpos]])
match匹配從字符串的開頭匹配,regex對象match方法可以重設(shè)定開始位置和結(jié)束位置,返回match對象
import re
s = '''bottle\nbag\nbig\nable'''

# ===match===
result = re.match('b',s)  # 找到一個就不找了
print(1,result) # bottle
print(2,type(result))
result = re.match('a',s) # 沒找到,返回None
print(3,result)
result = re.match('^a',s,re.M) # 依然從頭開始找,多行模式?jīng)]有用
print(4,result)
result = re.match('^a',s,re.S) # 依然從頭開始找
print(5,result)

運行結(jié)果:
1 <_sre.SRE_Match object; span=(0, 1), match='b'>
2 <class '_sre.SRE_Match'>
3 None
4 None
5 None

# 先編譯,然后使用正則表達式對象
regex = re.compile('a')
result = regex.match(s)
print(1,result)
result = regex.match(s,15)
print(2,result)

# 運行結(jié)果
1 None
2 <_sre.SRE_Match object; span=(15, 16), match='a'>

2.search:

re.search(pattern,string,flags=0)
regex.search(string[,pos[,endpos]])
從頭搜索直到第一個匹配,regex對象search方法可以重設(shè)定開始位置和結(jié)束位置,返回match對象
import re
s = '''bottle\nbag\nbig\nable'''

# ===search===
result = re.search('a',s)  # 掃描找到匹配的第一個位置
print(1,result)  # apple
regex = re.compile('b')
result = regex.search(s,1)
print(2,result)  # bag
regex = re.compile('^b',re.M)
result = regex.search(s) # 不管是不是多行,找到就返回
print(3,result)  # bottle
result = regex.search(s,8)
print(4,result)  # big

# 運行結(jié)果
1 <_sre.SRE_Match object; span=(8, 9), match='a'>
2 <_sre.SRE_Match object; span=(7, 8), match='b'>
3 <_sre.SRE_Match object; span=(0, 1), match='b'>
4 <_sre.SRE_Match object; span=(11, 12), match='b'>

3.fullmatch:

re.fullmatch(pattern,string,flags=0)
regex.fullmatch(string[,pos[,endpos]])
import re

s = '''bottle\nbag\nbig\nable'''

# ===fullmatch===
result = re.fullmatch('bag',s)
print(1,result)
regex = re.compile('bag')
result = regex.fullmatch(s)
print(2,result)
result = regex.fullmatch(s,7)
print(3,result)
result = regex.fullmatch(s,7,10)  # 要完全匹配,多了少了都不行[7,10)
print(4,result) 

# 運行結(jié)果
1 None
2 None
3 None
4 <_sre.SRE_Match object; span=(7, 10), match='bag'>

3.全文搜索

1.findall:

re.findall(pattern,string,flags=0)
regex.findall(string[,pos[,endpos]])
對整個字符串,從左至右匹配,返回所有匹配項的列表
import re

s = '''bottle\nbag\nbig\nable'''

# ===findall方法===
result = re.findall('b',s)
print(1,result)
regex = re.compile('^b')
result = regex.findall(s)
print(2,result)
regex = re.compile('^b',re.M)
result = regex.findall(s,7)
print(3,result)
regex = re.compile('^b',re.S)
result = regex.findall(s)
print(4,result)
regex = re.compile('^b',re.M)
result = regex.findall(s,7,10)
print(5,result)

# 運行結(jié)果
1 ['b', 'b', 'b', 'b']
2 ['b']
3 ['b', 'b']
4 ['b']
5 ['b']

2.finditer:

re.finditer(pattern,string,flags=0)
regex.finditer(string[,pos[,endpos]])
對整個字符串,從左至右匹配,返回所有匹配項,返回迭代器。
注意:每次迭代返回的是match對象
import re

s = '''bottle\nbag\nbig\nable'''

# ===finditer方法===
regex = re.compile('^b',re.M)
result = regex.finditer(s)
print(0,type(result))

for i,x in enumerate(result,1):  # enumerate用法,遍歷時,前面元素位索引,后面位迭代的值
    print(i,x)

# 運行結(jié)果
0 <class 'callable_iterator'>
1 <_sre.SRE_Match object; span=(0, 1), match='b'>
2 <_sre.SRE_Match object; span=(7, 8), match='b'>
3 <_sre.SRE_Match object; span=(11, 12), match='b'>

4.匹配替換

1.sub:

re.sub(pattern,replacement,string,count=0,flags=0)
regex.sub(replacement,string,count=0)
使用pattern對字符串string進行匹配,對匹配項使用repl替換。
replacement可以是string、bytes、function

2.subn:

re.subn(pattern,replacement,string,count=0,flags=0)
regex.subn(replacement,string,count=0)
同sub返回一個元組(new_string , number_of_subs_made)
import re

s = '''bottle\nbag\nbig\nable'''

# ===sub方法===
regex = re.compile('b\wg')
result = regex.sub('stone',s)
print(1,result.replace('\n',','))  # 被替換后的字符串
result = regex.sub('stone',s,1)  # 替換1次
print(2,result.replace('\n',','))

# ===subn方法===
regex = re.compile('\s+')
result = regex.subn('\t',s)
print(3,result)

# 運行結(jié)果
1 bottle,stone,stone,able
2 bottle,stone,big,able
3 ('bottle\tbag\tbig\table', 3)

5.分割字符串

1.split:

字符串的分割函數(shù),太難用,不能指定多個字符進行分割
re.split(pattern,string,maxsplit=0,flags=0)
re.split分割字符串
import re

s = '''01 bottle
02 bag
03       big1
100         able'''

# ===split方法,把每行單詞提取出來===
print(0,s.split())
result = re.split('[\s\d]+',s)
print(1,result)

regex = re.compile('^[\s\d]+')
result = regex.split(s)
print(2,result)

regex = regex.split(s)
print(3,result)

regex = re.compile('\s+|(?<!\w)\d+')
result = regex.split(s)
print(4,result)

regex = re.compile('\s+\d+\s+')
result = regex.split(' ' + s)
print(5,result)

# 運行結(jié)果
0 ['01', 'bottle', '02', 'bag', '03', 'big1', '100', 'able']
1 ['', 'bottle', 'bag', 'big', 'able']
2 ['', 'bottle\n02 bag\n03       big1\n100         able']
3 ['', 'bottle\n02 bag\n03       big1\n100         able']
4 ['', '', '', 'bottle', '', '', 'bag', '', '', 'big1', '', '', 'able']
5 ['', 'bottle', 'bag', 'big1', 'able']

6.分組

使用小括號的pattern捕獲的數(shù)據(jù)被放到了組group中。match、search函數(shù)可以返回match對象;findall返回字符串列表;finditer返回一個個match對象
如果pattern中使用了分組,如果有匹配的結(jié)果,會在match對象中
1.使用group(N)方式返回對應(yīng)分組,1-N是對應(yīng)的分組,0返回整個匹配的字符串
2.如果使用了命名分組,可以使用group('name')的方式取分組
3.也可以使用groups()返回所有組
4.使用groupdict()返回所有命名的分組
import re

s = '''bottle\nbag\nbig\napple'''

# 分組
regex = re.compile('(b\w+)')
result = regex.match(s)
print(0,type(result))
print(1,'match',result.groups())

result = regex.search(s,1)
print(2,'search',result.groups())

# 命名分組
regex = re.compile('(b\w+)\n(?P<name2>b\w+)\n(?P<name3>b\w+)')
result = regex.match(s)
print(3,'match',result)
print(4,result.group(3),result.group(2),result.group(1))
print(5,result.group(0).encode())
print(6,result.group('name2'),result.group('name3'))
print(7,result.groups())
print(8,result.groupdict())

result = regex.findall(s)
for x in result:
    print('**',type(x),x)

regex = re.compile('(?P<head>b\w+)')
result = regex.finditer(s)
for x in result:
    print('==',type(x),x,x.group(),x.group('head'))

# 運行結(jié)果
0 <class '_sre.SRE_Match'>
1 match ('bottle',)
2 search ('bag',)
3 match <_sre.SRE_Match object; span=(0, 14), match='bottle\nbag\nbig'>
4 big bag bottle
5 b'bottle\nbag\nbig'
6 bag big
7 ('bottle', 'bag', 'big')
8 {'name2': 'bag', 'name3': 'big'}
** <class 'tuple'> ('bottle', 'bag', 'big')
== <class '_sre.SRE_Match'> <_sre.SRE_Match object; span=(0, 6), match='bottle'> bottle bottle
== <class '_sre.SRE_Match'> <_sre.SRE_Match object; span=(7, 10), match='bag'> bag bag
== <class '_sre.SRE_Match'> <_sre.SRE_Match object; span=(11, 14), match='big'> big big
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容