Python-字串樣式比對

Python-字串樣式比對


首先必須先匯入re模組,有關regular expression的相關說明可參考http://en.wikipedia.org/wiki/Regular_expression


ex1: 比對字串樣式:句首為Wellcome中間有空格或tab隔開,句子結尾是here。括號中的字串會抓取到match.groups()中。要取出其中的每個字串,可以用match.group(i),i為要取出找到的第幾個字串。


>>> import re
>>> match=re.match('Wellcome[  \t]*(.*)here','Wellcome   to here')

>>> dir(match)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 's
pan', 'start']



>>> print match.groups()
('to ',)




>>> match.group(1)
'to '




ex2 取出字串樣式為'/(.*)/(.*)/(.*)’括號中的字串


>>> match=re.match('/(.*)/(.*)/(.*)','/usr/home/sample')
>>> match.groups()
('usr', 'home', 'sample')
>>> match.group(1)
'usr'
>>>