在python中,對正則表達式的支持是通過re模塊來支持的。使用re的步驟是先把表達式字符串編譯成pattern實例,然后在使用pattern去匹配文本獲取結果。
其實也有另外一種方式,就是直接使用re模塊的方法,但是這樣就不能使用編譯后的pattern實例了。
實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/usr/bin/python # -*- coding: utf-8 -*- import re pat = re. compile (r 'hello' ) match = pat.match( 'hello world!' ) if match: print match.group() match1 = re.match(r 'hello' , 'hello world!' ) if match1: print match1.group() print match1.pos |
返回的結果相同,都是 hello
關于Pattern 對象:
它是由re.complie函數來構造的,是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。
Pattern不能直接實例化,必須使用re.compile()進行構造。
Pattern提供了幾個可讀屬性用于獲取表達式的相關信息:
- pattern: 編譯時用的表達式字符串。
- flags: 編譯時用的匹配模式。數字形式。
- groups: 表達式中分組的數量。
- groupindex: 以表達式中有別名的組的別名為鍵、以該組對應的編號為值的字典,沒有別名的組不包含在內。
關于 re.compile方法
re.compile(strPattern[, flag]):
這個方法是Pattern類的工廠方法,用于將字符串形式的正則表達式編譯為Pattern對象。 第二個參數flag是匹配模式,取值可以使用按位或運算符'|'表示同時生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)與re.compile('(?im)pattern')是等價的。
可選值有:
- re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)
- M(MULTILINE): 多行模式,改變'^'和'$'的行為(參見上圖)
- S(DOTALL): 點任意匹配模式,改變'.'的行為
- L(LOCALE): 使預定字符類 \w \W \b \B \s \S 取決于當前區域設定
- U(UNICODE): 使預定字符類 \w \W \b \B \s \S \d \D 取決于unicode定義的字符屬性
- X(VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,并可以加入注釋
1).關于 match方法:
Match對象是一次匹配的結果,包含了很多關于此次匹配的信息,可以使用Match提供的可讀屬性或方法來獲取這些信息。
屬性:
- string: 匹配時使用的文本。
- re: 匹配時使用的Pattern對象。
- pos: 文本中正則表達式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
- endpos: 文本中正則表達式結束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
- lastindex: 最后一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將為None。
- lastgroup: 最后一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將為None。
方法:
1、group([group1, …]):
獲得一個或多個分組截獲的字符串;指定多個參數時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最后一次截獲的子串。
2、groups([default]):
以元組形式返回全部分組截獲的字符串。相當于調用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認為None。
3、groupdict([default]):
返回以有別名的組的別名為鍵、以該組截獲的子串為值的字典,沒有別名的組不包含在內。default含義同上。
4、start([group]):
返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認值為0。
5、end([group]):
返回指定的組截獲的子串在string中的結束索引(子串最后一個字符的索引+1)。group默認值為0。
6、span([group]):
返回(start(group), end(group))。
7、expand(template):
將匹配到的分組代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。\id與\g<id>是等價的;但\10將被認為是第10個分組,如果你想表達\1之后是字符'0',只能使用\g<1>0。
請看例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#!/usr/bin/python # -*- coding: utf-8 -*- import re m = re.match(r '(\w+)\s(\w+)' , 'aaa bbb ccc' ) print m.string print m.re print m.pos print m.endpos print m.lastindex print m.lastgroup print m.group() print m.start() print m.end() print m.span() print m.expand(r '\2 \1' ) |
結果為:
aaa bbb ccc
<_sre.SRE_Pattern object at 0x10dbfda08>
0
11
2
None
aaa bbb
0
7
(0, 7)
bbb aaa
2).關于search方法:
查找可以匹配的子串,和match 不同的是他不是從開始處開始匹配的。如果沒有匹配上,則返回None
上面的例子中,將match 換成search返回的結果一樣
請看:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/usr/bin/python # -*- coding: utf-8 -*- import re pat = re. compile (r 'hello' ) match = pat.match( 'shello world!' ) if match: print match.group() else : print 'not match!' match1 = re.search(r 'hello' , 'shello world!' ) if match1: print match1.group() |
結果為:
not match!
hello
這2個函數,沒有其他區別,就是一個是從開始匹配的,另外一個不是開始的
3.split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能夠匹配的子串將string分割后返回列表。maxsplit用于指定最大分割次數,不指定將全部分割。
4.findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。
5.finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。
6.sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替換string中每一個匹配的子串后返回替換后的字符串。
當repl是一個字符串時,可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),并返回一個字符串用于替換(返回的字符串中不能再引用分組)。
count用于指定最多替換次數,不指定時全部替換。
7.subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替換次數)。
例子為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/python # -*- coding: utf-8 -*- import re p = re. compile (r '\d+' ) print p.split( 'aa1bb2cc3dd4ee5ff6' ) print p.findall( 'aa1bb2cc3dd4ee5ff6' ) for m in p.finditer( 'aa1bb2cc3dd4ee5ff6' ): print m.group(), print '\nsub test' p1 = re. compile (r '(\w+)\s+(\w+)' ) s = 'i am ok' print p1.sub(r '\2 \1' ,s) print p1.subn(r '\2 \1' ,s) |
結果:
['aa', 'bb', 'cc', 'dd', 'ee', 'ff', '']
['1', '2', '3', '4', '5', '6']
1 2 3 4 5 6
sub test
am i ok
('am i ok', 1)
以上就是本文的全部內容,希望對大家的學習有所幫助。