1. 程式人生 > >【Python】re模組中re.match和re.search用法總結

【Python】re模組中re.match和re.search用法總結

###Date: 2018-1-6

###Author: SoaringLee

==========================================================================

re模組是正則表示式模組,用於採用某種規則進行匹配或者尋找相應物件。

re.match

re.match(pattern,string[,flags])

作用:從首字母開始開始匹配,string如果包含pattern子串,則匹配成功,返回Match物件,失敗則返回None,若要完全匹配,pattern要以$結尾。

Example:

>>> print re.match('abc','abcdef').group()
abc

re.search

re.search(pattern,string[,flags])
作用:若string中包含pattern子串,則返回Match物件,否則返回None,注意,如果string中存在多個pattern子串,只返回第一個。

Example:

>>> print re.search('[0-9]*x[0-9]*','1920x1080').group()
1920x1080

>>> print re.search('([0-9]*)x([0-9]*)','1920x1080').group(0)
1920x1080
>>> print re.search('([0-9]*)x([0-9]*)','1920x1080').group(1)
1920
>>> print re.search('([0-9]*)x([0-9]*)','1920x1080').group(2)
1080

參考:

 https://www.cnblogs.com/tina-python/p/5508402.html