1. 程式人生 > >正則表示式—— Pattern 物件的常用方法

正則表示式—— Pattern 物件的常用方法

match 方法

match 方法用於查詢字串的頭部(也可以指定起始位置),它是一次匹配,只要找到了一個匹配的結果就返回,而不是查詢所有匹配的結果。它的一般使用形式如下:

match(string[, pos[, endpos]])

其中,string 是待匹配的字串,pos 和 endpos 是可選引數,指定字串的起始和終點位置,預設值分別是 0 和 len (字串長度)。因此,當你不指定 pos 和 endpos 時,match 方法預設匹配字串的頭部。

當匹配成功時,返回一個 Match 物件,如果沒有匹配物件,則返回 None。

>>> import re
>>> pattern = re.compile(r'\d+')  # 用於匹配至少一個數字

>>> m = pattern.match('one12twothree34four')  # 查詢頭部,沒有匹配
>>> print m
None

>>> m = pattern.match('one12twothree34four', 2, 10) # 從'e'的位置開始匹配,沒有匹配
>>> print m
None

>>> m = pattern.match('one12twothree34four', 3, 10) # 從'1'的位置開始匹配,正好匹配
>>> print m                                         # 返回一個 Match 物件
<_sre.SRE_Match object at 0x10a42aac0>

>>> m.group(0)   # 可省略 0
'12'
>>> m.start(0)   # 可省略 0
3
>>> m.end(0)     # 可省略 0
5
>>> m.span(0)    # 可省略 0
(3, 5)

在上面,當匹配成功時返回一個 Match 物件,其中:

group([group1, …]) 方法用於獲得一個或多個分組匹配的字串,當要獲得整個匹配的子串時,可直接使用 group() 或 group(0);

start([group]) 方法用於獲取分組匹配的子串在整個字串中的起始位置(子串第一個字元的索引),引數預設值為 0;

end([group]) 方法用於獲取分組匹配的子串在整個字串中的結束位置(子串最後一個字元的索引+1),引數預設值為 0;

span([group]) 方法返回 (start(group), end(group))。

search 方法

search 方法用於查詢字串的任何位置,它也是一次匹配,只要找到了一個匹配的結果就返回,而不是查詢所有匹配的結果,它的一般使用形式如下:

search(string[, pos[, endpos]])

其中,string 是待匹配的字串,pos 和 endpos 是可選引數,指定字串的起始和終點位置,預設值分別是 0 和 len (字串長度)。
當匹配成功時,返回一個 Match 物件,如果沒有匹配上,則返回 None。

>>> import re
>>> pattern = re.compile('\d+')
>>> m = pattern.search('one12twothree34four')  # 這裡如果使用 match 方法則不匹配
>>> m
<_sre.SRE_Match object at 0x10cc03ac0>
>>> m.group()
'12'
>>> m = pattern.search('one12twothree34four', 10, 30)  # 指定字串區間
>>> m
<_sre.SRE_Match object at 0x10cc03b28>
>>> m.group()
'34'
>>> m.span()
(13, 15)

findall 方法

上面的 match 和 search 方法都是一次匹配,只要找到了一個匹配的結果就返回。然而,在大多數時候,我們需要搜尋整個字串,獲得所有匹配的結果。
findall 方法的使用形式如下:

findall(string[, pos[, endpos]])

其中,string 是待匹配的字串,pos 和 endpos 是可選引數,指定字串的起始和終點位置,預設值分別是 0 和 len (字串長度)。
findall 以列表形式返回全部能匹配的子串,如果沒有匹配,則返回一個空列表。

import re
pattern = re.compile(r'\d+')   # 查詢數字

result1 = pattern.findall('hello 123456 789')
result2 = pattern.findall('one1two2three3four4', 0, 10)

print(result1)
print(result2)

執行結果:

['123456', '789']
['1', '2']

finditer 方法

finditer 方法的行為跟 findall 的行為類似,也是搜尋整個字串,獲得所有匹配的結果。但它返回一個順序訪問每一個匹配結果(Match 物件)的迭代器。

import re
pattern = re.compile(r'\d+')

result_iter1 = pattern.finditer('hello 123456 789')
result_iter2 = pattern.finditer('one1two2three3four4', 0, 10)

print(type(result_iter1))
print(type(result_iter2))

print('result1...')
for m1 in result_iter1:   # m1 是 Match 物件
    print('matching string: {}, position: {}'.format(m1.group(), m1.span()))

print('result2...')
for m2 in result_iter2:
    print('matching string: {}, position: {}'.format(m2.group(), m2.span()))

執行結果:

<type 'callable-iterator'>
<type 'callable-iterator'>
result1...
matching string: 123456, position: (6, 12)
matching string: 789, position: (13, 16)
result2...
matching string: 1, position: (3, 4)
matching string: 2, position: (7, 8)

split 方法

split 方法按照能夠匹配的子串將字串分割後返回列表,它的使用形式如下:

split(string[, maxsplit])

其中,maxsplit 用於指定最大分割次數,不指定將全部分割。

import re
p = re.compile(r'[\s\,\;]+')
print(p.split('a,b;; c   d'))

執行結果:

['a', 'b', 'c', 'd']

sub 方法

sub 方法用於替換。它的使用形式如下:

sub(repl, string[, count])

其中,repl 可以是字串也可以是一個函式:
如果 repl 是字串,則會使用 repl 去替換字串每一個匹配的子串,並返回替換後的字串,另外,repl 還可以使用 id 的形式來引用分組,但不能使用編號 0;
如果 repl 是函式,這個方法應當只接受一個引數(Match 物件),並返回一個字串用於替換(返回的字串中不能再引用分組)。
count 用於指定最多替換次數,不指定時全部替換。

import re
p = re.compile(r'(\w+) (\w+)') #
s = 'hello 123, hello 456'

print(p.sub(r'hello world', s))  # 使用 'hello world' 替換 'hello 123' 和 'hello 456'
print(p.sub(r'\2 \1', s))        # 引用分組

def func(m):
    return 'hi' + ' ' + m.group(2)

print(p.sub(func, s))
print(p.sub(func, s, 1))         # 最多替換一次

執行結果:

hello world, hello world
123 hello, 456 hello
hi 123, hi 456
hi 123, hello 456

匹配中文

在某些情況下,我們想匹配文字中的漢字,有一點需要注意的是,中文的 unicode 編碼範圍 主要在 [u4e00-u9fa5],這裡說主要是因為這個範圍並不完整,比如沒有包括全形(中文)標點,不過,在大部分情況下,應該是夠用的。

假設現在想把字串 title = u’你好,hello,世界’ 中的中文提取出來,可以這麼做:

import re

title = u'你好,hello,世界'
pattern = re.compile(r'[\u4e00-\u9fa5]+')
result = pattern.findall(title)

print(result)

執行結果:

['你好', '世界']