天天看點

re Python正則

re.compile() 生成正則對象效率最高

<col>

# encoding: UTF-8

import re

# 将正規表達式編譯成Pattern對象

pattern = re.compile(r'hello')

# 使用Pattern比對文本,獲得比對結果,無法比對時将傳回None

match = pattern.match('hello world!')

if match:

    # 使用Match獲得分組資訊

    print match.group()

### 輸出 ###

# hello

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

2

3

4

a = re.compile(r"""\d +  # the integral part

                   \.    # the decimal point

                   \d *  # some fractional digits""", re.X)

b = re.compile(r"\d+\.\d*")

re提供了衆多子產品方法用于完成正規表達式的功能。這些方法可以使用Pattern執行個體的相應方法替代,唯一的好處是少寫一行re.compile()代碼,但同時也無法複用編譯後的Pattern對象。這些方法将在Pattern類的執行個體方法部分一起介紹。如上面這個例子可以簡寫為:

m = re.match(r'hello', 'hello world!')

print m.group()

re子產品還提供了一個方法escape(string),用于将string中的正規表達式元字元如*/+/?等之前加上轉義符再傳回,在需要大量比對元字元時有那麼一點用。

Match對象是一次比對的結果,包含了很多關于此次比對的資訊,可以使用Match提供的可讀屬性或方法來擷取這些資訊。

屬性:

string: 比對時使用的文本。

re: 比對時使用的Pattern對象。

pos: 文本中正規表達式開始搜尋的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。

endpos: 文本中正規表達式結束搜尋的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。

lastindex: 最後一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,将為None。

lastgroup: 最後一個被捕獲的分組的别名。如果這個分組沒有别名或者沒有被捕獲的分組,将為None。

方法:

group([group1, …]):

獲得一個或多個分組截獲的字元串;指定多個參數時将以元組形式傳回。group1可以使用編号也可以使用别名;編号0代表整個比對的子串;不填寫參數時,傳回group(0);沒有截獲字元串的組傳回None;截獲了多次的組傳回最後一次截獲的子串。

groups([default]):

以元組形式傳回全部分組截獲的字元串。相當于調用group(1,2,…last)。default表示沒有截獲字元串的組以這個值替代,預設為None。

groupdict([default]):

傳回以有别名的組的别名為鍵、以該組截獲的子串為值的字典,沒有别名的組不包含在内。default含義同上。

start([group]):

傳回指定的組截獲的子串在string中的起始索引(子串第一個字元的索引)。group預設值為0。

end([group]):

傳回指定的組截獲的子串在string中的結束索引(子串最後一個字元的索引+1)。group預設值為0。

span([group]):

傳回(start(group), end(group))。

expand(template):

将比對到的分組代入template中然後傳回。template中可以使用\id或\g&lt;id&gt;、\g&lt;name&gt;引用分組,但不能使用編号0。\id與\g&lt;id&gt;是等價的;但\10将被認為是第10個分組,如果你想表達\1之後是字元'0',隻能使用\g&lt;1&gt;0。

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

m = re.match(r'(\w+) (\w+)(?P&lt;sign&gt;.*)', 'hello world!')

print "m.string:", m.string

print "m.re:", m.re

print "m.pos:", m.pos

print "m.endpos:", m.endpos

print "m.lastindex:", m.lastindex

print "m.lastgroup:", m.lastgroup

print "m.group(1,2):", m.group(1, 2)

print "m.groups():", m.groups()

print "m.groupdict():", m.groupdict()

print "m.start(2):", m.start(2)

print "m.end(2):", m.end(2)

print "m.span(2):", m.span(2)

print r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3')

### output ###

# m.string: hello world!

# m.re: &lt;_sre.SRE_Pattern object at 0x016E1A38&gt;

# m.pos: 0

# m.endpos: 12

# m.lastindex: 3

# m.lastgroup: sign

# m.group(1,2): ('hello', 'world')

# m.groups(): ('hello', 'world', '!')

# m.groupdict(): {'sign': '!'}

# m.start(2): 6

# m.end(2): 11

# m.span(2): (6, 11)

# m.expand(r'\2 \1\3'): world hello!

Pattern對象是一個編譯好的正規表達式,通過Pattern提供的一系列方法可以對文本進行比對查找。

Pattern不能直接執行個體化,必須使用re.compile()進行構造。

Pattern提供了幾個可讀屬性用于擷取表達式的相關資訊:

pattern: 編譯時用的表達式字元串。

flags: 編譯時用的比對模式。數字形式。

groups: 表達式中分組的數量。

groupindex: 以表達式中有别名的組的别名為鍵、以該組對應的編号為值的字典,沒有别名的組不包含在内。

p = re.compile(r'(\w+) (\w+)(?P&lt;sign&gt;.*)', re.DOTALL)

print "p.pattern:", p.pattern

print "p.flags:", p.flags

print "p.groups:", p.groups

print "p.groupindex:", p.groupindex

# p.pattern: (\w+) (\w+)(?P&lt;sign&gt;.*)

# p.flags: 16

# p.groups: 3

# p.groupindex: {'sign': 3}

執行個體方法[ | re子產品方法]:

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):

這個方法将從string的pos下标處起嘗試比對pattern;如果pattern結束時仍可比對,則傳回一個Match對象;如果比對過程中pattern無法比對,或者比對未結束就已到達endpos,則傳回None。

pos和endpos的預設值分别為0和len(string);re.match()無法指定這兩個參數,參數flags用于編譯pattern時指定比對模式。

注意:這個方法并不是完全比對。當pattern結束時若string還有剩餘字元,仍然視為成功。想要完全比對,可以在表達式末尾加上邊界比對符'$'。

示例參見2.1小節。

search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):

這個方法用于查找字元串中可以比對成功的子串。從string的pos下标處起嘗試比對pattern,如果pattern結束時仍可比對,則傳回一個Match對象;若無法比對,則将pos加1後重新嘗試比對;直到pos=endpos時仍無法比對則傳回None。

pos和endpos的預設值分别為0和len(string));re.search()無法指定這兩個參數,參數flags用于編譯pattern時指定比對模式。

1. import re

2.  

3. # 将正規表達式編譯成Pattern對象

4. pattern = re.compile(r'world')

5.  

6. # 使用search()查找比對的子串,不存在能比對的子串時将傳回None

7. # 這個例子中使用match()無法成功比對

8. match = pattern.search('hello world!')

9.  

10. if match:

11.     # 使用Match獲得分組資訊

12.     print match.group()

13.  

14. ### 輸出 ###

15. # world

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):

按照能夠比對的子串将string分割後傳回清單。maxsplit用于指定最大分割次數,不指定将全部分割。

1.  

2. p = re.compile(r'\d+')

3. print p.split('one1two2three3four4')

4.  

5. ### output ###

6. # ['one', 'two', 'three', 'four', '']

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):

搜尋string,以清單形式傳回全部能比對的子串。

3. p = re.compile(r'\d+')

4. print p.findall('one1two2three3four4')

6. ### output ###

7. # ['1', '2', '3', '4'

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):

搜尋string,傳回一個順序通路每一個比對結果(Match對象)的疊代器。

p = re.compile(r'\d+')

for m in p.finditer('one1two2three3four4'):

    print m.group(),

# 1 2 3 4

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):

使用repl替換string中每一個比對的子串後傳回替換後的字元串。

當repl是一個字元串時,可以使用\id或\g&lt;id&gt;、\g&lt;name&gt;引用分組,但不能使用編号0。

當repl是一個方法時,這個方法應當隻接受一個參數(Match對象),并傳回一個字元串用于替換(傳回的字元串中不能再引用分組)。

count用于指定最多替換次數,不指定時全部替換。

1.import re

2. p = re.compile(r'(\w+) (\w+)')

3. s = 'i say, hello world!'

5. print p.sub(r'\2 \1', s)

6.  

7. def func(m):

8.     return m.group(1).title() + ' ' + m.group(2).title()

10. print p.sub(func, s)

11.  

12. ### output ###

13. # say i, world hello!

14. # I Say, Hello World!

subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):

傳回 (sub(repl, string[, count]), 替換次數)。

p = re.compile(r'(\w+) (\w+)')

s = 'i say, hello world!'

print p.subn(r'\2 \1', s)

def func(m):

    return m.group(1).title() + ' ' + m.group(2).title()

print p.subn(func, s)

# ('say i, world hello!', 2)

# ('I Say, Hello World!', 2

re Python正則