1、正則表達式概述
Regular Expression 縮寫為regex, regexp, RE等,也可以叫規則表達式。是對字符串和特殊字符操作的一種邏輯。采用事先定義的字符串和字符組合,組成一個規則字符串來過濾邏輯。
2、用途
通常被用來檢索、替換那些符合某個規則的文本。
3、具體實例(python中用法)
### match和search用法
#### import re 導入模塊
“””
s = ”’The\nquick\nbrown\nfox\njumps\nover\na\nlazy\ndog”’
for x in s:
pass
result1 = re.match(‘T’,s)
result2 = re.match(‘h’,s) None
result3 = re.match(‘^q’,s,re.M) None
result4 = re.match(‘^b’,s,re.S) None
result5 = re.search(‘a’,s)
result6 = re.search(‘y’,s,re.M)
編譯之后的匹配
regex = re.compile(‘f’)
result7 = regex.match(s) 還是從頭找
result8 = regex.match(s,16) 位置剛好的時候可以找到
result9 = regex.search(s) 找到就返回,忽略單行和多行
print(result1,’\n’,result2,’\n’,result3,’\n’,result4,’\n’,result5,’\n’,result6,’\n’,result7,’\n’,result8,’\n’,result9)
輸出結果為:
<_sre.SRE_Match object; span=(0, 1), match=’T’>
None
None
None
<_sre.SRE_Match object; span=(31, 32), match=’a’>
<_sre.SRE_Match object; span=(36, 37), match=’y’>
None
<_sre.SRE_Match object; span=(16, 17), match=’f’>
<_sre.SRE_Match object; span=(16, 17), match=’f’>
“”””
## 全部查找:
### findall的方法:
“””
import re
findall(pattern,string,flags=0)
對整個字符串,從左至右匹配,返回所有匹配項的列表
s = ”’The\nquick\nbrown\nfox\njumps\nover\na\nlazy\ndog”’
for x in s:
pass
result = re.findall(‘u’,s) 匹配到所有的u,然后返回一個所有匹配到u的列表
regex = re.compile(‘^T’) 如果把T換成后面的字母,會發現返回結果為空列表。
result1 = regex.findall(s) 把字符看成一個整體,返回一個空列表。
regex1 = re.compile(‘^b’,re.M)
result2 = regex1.findall(s) 多行模式可以找到
regex2 = re.compile(‘^b’,re.S) 單行模式無法找到,也就是說這個字符串被看成一個整體,返回空列表
result3 = regex2.findall(s)
regex3 = re.compile(‘o’,re.M)
result4 = regex3.findall(s,5,18) 如果限定了位置的話,只會找限定以內的,返回列表
print(result,result1,result2,result3,result4)
打印結果為:
[‘u’, ‘u’]
[‘T’]
[‘b’]
[]
[‘o’, ‘o’]
“””
#### finditer方法:
“””
import re
finditer(pattern,string,flags=0)
regex.finditer(string[,pos[,endpos]])
對整個字符串,從左至右匹配,返回所有匹配項,返回迭代器
需要注意的是每次返回的都match對象
s = ”’The\nquick\nbrown\nfox\njumps\nover\na\nlazy\ndog”’
for x in s:
pass
regex = re.compile(‘o’)
result = regex.finditer(s)
print(type(result)) 可調用的迭代對象
print(next(result)) 返回的結果是match對象
print(next(result)) 返回match對象
打印結果為:
<class ‘callable_iterator’>
<_sre.SRE_Match object; span=(12, 13), match=’o’>
<_sre.SRE_Match object; span=(17, 18), match=’o’>
“””
#### fullmatch方法
“””
s = ”’The\nquick\nbrown\nfox\njumps\nover\na\nlazy\ndog”’
for x in s:
pass
result = re.fullmatch(‘j’,s)
regex = re.compile(‘q’)
result1 = regex.fullmatch(s)
result2 = regex.fullmatch(s,4,5) 要完全匹配,多了少了都不行
result3 = regex.fullmatch(s,4)
print(result,’\n’,result1,’\n’,result2,’\n’,result3)
打印結果為:
None
None
<_sre.SRE_Match object; span=(4, 5), match=’q’>
None
“””
#### split用法:
“””
1、分割字符串
2、字符串的分割函數不怎么好用,不能指定多個分隔符進行分割。
3、re.split(pattern,string,maxsplit=0,flags=0)
4、re.split分割字符串
import re
s = ”’ 01 bottle 02 bag 03 big 200 apple”’
for x in s:
pass
把每行的單詞都提取出來
print(s.split())
返回結果:[’01’, ‘bottle’, ’02’, ‘bag’, ’03’, ‘big’, ‘200’, ‘apple’]
發現若把單詞提取出來,僅僅split是不行的
result = re.split(‘[\s\d]+’, s) 字符串首,正則空白或者數字至少重復一次(括號內,至少有一個空白或者數字)
print(result)
regex = re.compile(‘^[\s\d]+’) 字符串首
result1 = regex.split(s)
print(result1)
regex1 = re.compile(‘^[\s\d]+’,re.M)
result2 = regex1.split(s)
print(result2)
regex2 = re.compile(‘\s+\d+\s+’) 空白數字空白
result3 = regex2.split(‘ ‘+s) 因為都是字符串,所以可以直接相加
print(result3)
打印結果為:
[’01’, ‘bottle’, ’02’, ‘bag’, ’03’, ‘big’, ‘200’, ‘apple’]
[”, ‘bottle’, ‘bag’, ‘big’, ‘apple’]
[”, ‘bottle 02 bag 03 big 200 apple’]
[”, ‘bottle 02 bag 03 big 200 apple’]
[”, ‘bottle’, ‘bag’, ‘big’, ‘apple’]
“””
#### 匹配替換:
“””
re.sub(pattern,replacement,string,count=0,flags=0)
regex.sub(replacement,string,count=0)
使用pattern對字符串string進行匹配,對匹配項使用repl替換
replacement可以是string、bytes、function
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\napple”’
for x in s:
pass
替換方法
regex = re.compile(‘b\wg’)
result = regex.sub(‘Eric’, s)
print(result,end=”) 替換后返回結果是:bottle Eric Eric apple
result1 = regex.sub(‘telephone’, s, 1) 被替換1次
print(result1)
regex1 = re.compile(‘\s+’)
result2 = regex1.subn(‘ ‘, s)
print(result2) 返回一個元組和被替換的次數,(‘bottle bag big apple’, 3)
打印結果為:
bottle
Eric
Eric
applebottle
telephone
big
apple
(‘bottle bag big apple’, 3)
“””
#### 分組:
“””
使用分組把捕獲到的數據放到了group中
match、search函數可以返回match對象;findall返回字符串列表;finditer返回一個個match對象
1、使用group(N)返回對應分組,1-N是對應分組,0返回整個匹配字符串
2、可以使用group(‘name’)取分組
3、使用groups()返回所有分組
4、使用groupdict()返回所有命名的分組
import re
s = ”’bottle\nbage\nbig\napple”’
for x in s:
pass
分組
regex = re.compile(‘(b\w+)’)
reuslt = regex.match(s)
print(1, type(reuslt))
print(2, ‘match’,reuslt.groups())
reuslt1 = regex.search(s,1) 限定匹配的起始位置
print(3, ‘search’, reuslt1.groups())
regex1 = re.compile(‘(b\w+)\\n(?P<name2>b\w+)\\n(?P<name3>b\w+)’) 這里轉義不轉義暫時測試沒有影響
reuslt2 = regex1.match(s)
print(4, reuslt2, ‘match’)
print(5, reuslt2.group(3), reuslt2.group(2), reuslt2.group(1)) 這樣打印報錯:IndexError: no such group
print(5, reuslt2.group(‘name2’)) 造成上面報錯的原因是打印的時候應該加上引號,因為名字為一個str(字符串)
print(type(‘name2’))
print(6, reuslt2.groupdict())
打印結果為:
1 <class ‘_sre.SRE_Match’>
2 match (‘bottle’,)
3 search (‘bage’,)
4 <_sre.SRE_Match object; span=(0, 15), match=’bottle\nbage\nbig’> match
5 bage
<class ‘str’>
6 {‘name2’: ‘bage’, ‘name3’: ‘big’}
“””
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/88221