在編寫處理網(wǎng)頁文本的程序時,經(jīng)常會有查找符合某些復(fù)雜規(guī)則的字符串的需要,正則表達(dá)式就是描述這些規(guī)則的工具枫攀。
基本語法和使用
1.常用元字符
元字符 | 含義 |
---|---|
. | 匹配除換行符以外的任意字符 |
\b | 匹配單詞的開始或結(jié)束 |
\d | 匹配數(shù)字 |
\w | 匹配字母必指、數(shù)字囊咏、下劃線或漢字 |
\s | 匹配任意空白符,包括空格、制表符梅割、換行符霜第、中文全角空格等 |
^ | 匹配字符串的開始 |
$ | 匹配字符串的結(jié)束 |
2.字符轉(zhuǎn)義
使用’\’作為轉(zhuǎn)義字符。
3.重復(fù)
限定符 | 含義 |
---|---|
* | 重復(fù)0次或更多次 |
+ | 重復(fù)1次或更多次 |
? | 重復(fù)0次或者1次 |
{n} | 重復(fù)n次 |
{n,} | 重復(fù)n次或更多次 |
{n,m} | 重復(fù)n到m次 |
4.字符集合
- [0-9]與\d等價
- [a-z0-9A-Z]與\w等價
5.分支條件
例:電話號碼中有一種是3位區(qū)號户辞,8位本地號(010-11223344)泌类,另一種是4位區(qū)號,7位本地號(0321-1234567)底燎;這時需要用到分支條件:0\d{2}-\d{8} | 0\d{3}-\d{7}
從左到右依次匹配刃榨,前面的條件滿足了就不看后面的了,條件之間是一種或的關(guān)系双仍。
6.分組
例:匹配192.168.1.1這樣的IP地址枢希。
((\d{1,3})\.){3}\d{1,3}
。但是這樣有可能出現(xiàn)333.444.555.666這樣的IP地址所以是不合理的朱沃。
以下才是合理的表示方式苞轿。
((25[0-5] | 2[0-4]\d[0-1]\d{2} | [1-9]?\d)\.){3}((25[0-5] | 2[0-4]\d[0-1]\d{2} | [1-9]?\d)\.)
7.反義
代碼 | 含義 |
---|---|
\W | 匹配任意不是字母、數(shù)字逗物、下劃線搬卒、漢字的字符 |
\S | 匹配任意不是空白符的字符 |
\D | 匹配任意非數(shù)字的字符 |
\B | 匹配不是單詞開頭或結(jié)束的位置 |
[^a] | 匹配除了a以外的任意字符 |
[^abcde] | 匹配除了a、b翎卓、c秀睛、d、e這幾個字母以外的任意字符 |
[^(123 莲祸!abc)] | 匹配除了a、b椭迎、c和1锐帜、2、3這幾個字符以外的任意字符 |
8.后向引用
9.零寬斷言
10.注釋
(?#comment)
例如:\b\w+(?#字符串)\b
11.貪婪與懶惰
12.處理選項
python與正則
1.re.match(pattern,string[,flags])
代碼:
import re
# 將正則表達(dá)式編譯成pattern對象
pattern = re.compile(r'\d+')
# 使用re.match匹配文本畜号,獲得匹配結(jié)果缴阎,無法匹配時將返回None
result1 = re.match(pattern,'192abc')
if result1:
print(result1.group())
else:
print('匹配失敗1')
result2 = re.match(pattern,'abc192')
print(result2)
if result2:
print(result2.group())
else:
print('匹配失敗2')
運(yùn)行結(jié)果:
192
None
匹配失敗2
2.re.search(pattern,string[,flags])
代碼:
import re
# 將正則表達(dá)式編譯成pattern對象
pattern = re.compile(r'dogs')
# 使用re.match匹配文本,獲得匹配結(jié)果简软,無法匹配時將返回None
result1 = re.match(pattern,'Cats are smarter than dogs')
if result1:
print(result1.group())
else:
print('匹配失敗1')
# 使用re.search匹配文本蛮拔,獲得匹配結(jié)果,無法匹配時將返回None
result2 = re.search(pattern,'Cats are smarter than dogs')
if result2:
print(result2.group())
else:
print('匹配失敗2')
運(yùn)行結(jié)果:
匹配失敗1
dogs
3.re.findall(pattern,string[,flags])
代碼:
import re
pattern = re.compile(r'\d+')
print(re.findall(pattern,'A1B2C3D4'))
運(yùn)行結(jié)果:
[‘1’, ‘2’, ‘3’, ‘4’]
4.re.finditer(pattern,string[,flags])
代碼:
import re
pattern = re.compile(r'\d+')
matchiter = re.finditer(pattern,'A1B2C3D4')
for match in matchiter:
print(match.group())
運(yùn)行結(jié)果:
1
2
3
4
5.re.sub(patter,repl,string[,count])
代碼:
import re
pattern = re.compile(r'(?P<word1>\w+) (?P<word2>\w+)') # 使用名稱引用
s = 'i say,hello world!'
print(pattern.sub(r'\g<word2> \g<word1>',s))
pattern = re.compile(r'(\w+) (\w+)')
print(pattern.sub(r'\2 \1',s)) # 使用編號
def func(m):
return m.group(1).title()+' '+m.group(2).title()
print(pattern.sub(func,s))
運(yùn)行結(jié)果:
say i,world hello!
say i,world hello!
I Say,Hello World!
6.re.subn(pattern,repl,string[,count])
代碼:
import re
s = 'i say,hello world!'
pattern = re.compile(r'(\w+) (\w+)')
print(pattern.subn(r'\2 \1',s))
def func(m):
return m.group(1).title()+' '+m.group(2).title()
print(pattern.subn(func,s))
運(yùn)行結(jié)果:
(‘say i,world hello!’, 2)
(‘I Say,Hello World!’, 2)
7.re.split(pattern,string[,maxsplit])
代碼:
import re
pattern = re.compile(r'\d+')
print(re.split(pattern,'A1B2C3D4'))
運(yùn)行結(jié)果:
[‘A’, ‘B’, ‘C’, ‘D’, ‘’]
Match對象的屬性和方法
代碼:
import re
pattern = re.compile(r'(\w+) (\w+) (?P<word>.*)')
match = pattern.match('I love you!')
print("match.string:",match.string)
print("match.re:",match.re)
print("match.pos:",match.pos)
print("match.endpos:",match.endpos)
print("match.lastindex:",match.lastindex)
print("match.lastgroup:",match.lastgroup)
print("match.group(1,2):",match.group(1,2))
print("match.groups():",match.groups())
print("match.groupdict():",match.groupdict())
print("match.start(2):",match.start(2))
print("match.end(2):",match.end(2))
print("match.span(2):",match.span(2))
print("match.expand(r'\\2 \\1 \\3'):",match.expand(r'\2 \1 \3'))
運(yùn)行結(jié)果:
match.string: I love you!
match.re: re.compile(‘(\w+) (\w+) (?P<word style="box-sizing: border-box;">.*)’)
match.pos: 0
match.endpos: 11
match.lastindex: 3
match.lastgroup: word
match.group(1,2): (‘I’, ‘love’)
match.groups(): (‘I’, ‘love’, ‘you!’)
match.groupdict(): {‘word’: ‘you!’}
match.start(2): 2
match.end(2): 6
match.span(2): (2, 6)
match.expand(r’\2 \1 \3’): love I you!</word>