Python實戰從入門到精通第九講——字符串與文本3之字符串匹配和搜索

匹配或者搜索特定模式的文本

匹配的是字面字符串,那麼你通常只需要調用基本字符串方法就行, 比如 str.find() , str.endswith() , str.startswith() 或者類似的方法:

>>> text = 'yeah, but no, but yeah, but no, but yeah'
>>> # Exact match
>>> text == 'yeah'
False
>>> # Match at start or end
>>> text.startswith('yeah')
True
>>> text.endswith('no')
False
>>> # Search for the location of the first occurrence
>>> text.find('no')
10

對於複雜的匹配需要使用正則表達式和 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

使用同一個模式去做多次匹配,你應該先將模式字符串預編譯爲模式對象。比如:

>>> 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

match() 總是從字符串開始去匹配,如果你想查找字符串任意部分的模式出現位置, 使用 findall() 方法去代替。比如:

>>> text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
>>> datepat.findall(text)
['11/27/2012', '3/13/2013']

在定義正則式的時候,通常會利用括號去捕獲分組。比如:

>>> 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()
>>>
>>> # Find all matches (notice splitting into tuples)
>>> 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

findall() 方法會搜索文本並以列表形式返回所有的匹配。 如果你想以迭代方式返回匹配,可以使用 finditer() 方法來代替,比如:

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

 

發佈了367 篇原創文章 · 獲贊 188 · 訪問量 51萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章