1. 程式人生 > >Python: 字符串搜索和匹配,re.compile() 編譯正則表達式字符串,然後使用match() , findall() 或者finditer() 等方法

Python: 字符串搜索和匹配,re.compile() 編譯正則表達式字符串,然後使用match() , findall() 或者finditer() 等方法

nth post cde clas import 預編譯 正則 一次 find

1. 使用find()方法

>>> text = ‘yeah, but no, but yeah, but no, but yeah‘

>>> text.find(‘no‘)
10

2. 使用re.match()

對於復雜的匹配需要使用正則表達式和re 模塊。為了解釋正則表達式的基本原理,假設想匹配數字格式的日期字符串比如11/27/2012 ,可以這樣做:
>>> text1 = ‘11/27/2012‘
>>> text2 = ‘Nov 27, 2012‘
>>>
>>> import re
>>> # Simple matching: \d+ means match one or more digits


>>> if re.match(r‘\d+/\d+/\d+‘, text1):
... print(‘yes‘)
... else:
... print(‘no‘)
...
yes
>>> if re.match(r‘\d+/\d+/\d+‘, text2):
... print(‘yes‘)
... else:
... print(‘no‘)
...
no

3.將字符串預編譯re.compile(),再match()

如果想使用同一個模式去做多次匹配,應該先將模式字符串預編譯為模式對象。比如:
>>> datepat = re.compile(r‘\d+/\d+/\d+‘)


>>> if datepat.match(text1):
... print(‘yes‘)
... else:
... print(‘no‘)
...
yes
>>> if datepat.match(text2):

... print(‘yes‘)
... else:
... print(‘no‘)
...
no

4.使用findall()方法

match() 總是從字符串開始去匹配,如果你想查找字符串任意部分的模式出現位置,使用findall() 方法去代替。比如:
>>> text = ‘Today is 11/27/2012. PyCon starts 3/13/2013.‘


>>> datepat.findall(text)
[‘11/27/2012‘, ‘3/13/2013‘]

5. .group()方法去捕獲分組


在定義正則式的時候,通常會利用括號去捕獲分組。比如:
>>> datepat = re.compile(r‘(\d+)/(\d+)/(\d+)‘)
捕捕獲分組可以使得後面的處理更加簡單,因為可以分別將每個組的內容提取出來。
比如:
>>> m = datepat.match(‘11/27/2012‘)
>>> m
<_sre.SRE_Match object at 0x1005d2750>
>>> # Extract the contents of each group
>>> m.group(0)
‘11/27/2012‘
>>> m.group(1)
‘11‘
>>> m.group(2)
‘27‘
>>> m.group(3)
‘2012‘
>>> m.groups()
(‘11‘, ‘27‘, ‘2012‘)
>>> month, day, year = m.groups()

>>> text
‘Today is 11/27/2012. PyCon starts 3/13/2013.‘
>>> datepat.findall(text)
[(‘11‘, ‘27‘, ‘2012‘), (‘3‘, ‘13‘, ‘2013‘)]
>>> for month, day, year in datepat.findall(text):
... print(‘{}-{}-{}‘.format(year, month, day))
...
2012-11-27
2013-3-13

6. 叠代方式返回finditer()

findall() 方法會搜索文本並以列表形式返回所有的匹配。如果你想以叠代方式返

>>> for m in datepat.finditer(text):
... print(m.groups())
...
(‘11‘, ‘27‘, ‘2012‘)
(‘3‘, ‘13‘, ‘2013‘)

核心步驟就是先使用re.compile() 編譯正則表達式字符串,然後使用match() , findall() 或者finditer() 等方法。

7. 精確匹配

如果你想精確匹配,確保你的正則表達式以$ 結尾,就像這麽這樣:
>>> datepat = re.compile(r‘(\d+)/(\d+)/(\d+)$‘)
>>> datepat.match(‘11/27/2012abcdef‘)
>>> datepat.match(‘11/27/2012‘)
<_sre.SRE_Match object at 0x1005d2750>
>>>

8.簡單的文本匹配/搜索

最後,如果你僅僅是做一次簡單的文本匹配/搜索操作的話,可以略過編譯部分,直接使用re 模塊級別的函數。比如:
>>> re.findall(r‘(\d+)/(\d+)/(\d+)‘, text)
[(‘11‘, ‘27‘, ‘2012‘), (‘3‘, ‘13‘, ‘2013‘)]
>>>
但是需要註意的是,如果你打算做大量的匹配和搜索操作的話,最好先編譯正則表達式,然後再重復使用它。模塊級別的函數會將最近編譯過的模式緩存起來,因此並會消耗太多的性能,但是如果使用預編譯模式的話,將會減少查找和一些額外的處理損耗

Python: 字符串搜索和匹配,re.compile() 編譯正則表達式字符串,然後使用match() , findall() 或者finditer() 等方法