標籤:對象 理解 工作 end ast class tar 集合 字元
re模組提供了3個方法對輸入的字串進行確切的查詢,match和search最多隻會返回一個匹配條件的子串,可以理解為非貪婪模式,而findall會返回N個匹配條件的子串,可以理解為貪婪模式
re.match()
re.search()
re.findall()
#match()方法的工作方式是只有當被搜尋字串的開頭匹配模式的時候它才能尋找到匹配對象,match返回的是對象,對象裡麵包含了很多資訊
match=re.match(r‘dog‘,‘dog cat dog‘) #只要匹配到滿足條件的就不匹配了print match.group(0) #dogprint match.start() #0print match.end() #3match=re.match(r‘cat‘,‘dog cat dog‘) print type(match) #<type ‘NoneType‘> #因為cat沒有在字串的開頭,所以沒有匹配到
#search()方法和match()類似,不過search()方法不會限制我們只從字串的開頭尋找匹配,它匹配子串,直到匹配到為止或者字串結束為止
match=re.search(r‘cat‘,‘dog cat dog‘)print match.group(0) #cat,如果不分組,預設就是第0組print match.start() #4print match.end() #7
#findall返回的是列表
match=re.findall(r‘dog‘, ‘dog cat dog‘) #匹配是整個字串,每個子串都要匹配,匹配到的字串剔除,後面的字串要繼續匹配正則條件,直到字串的結尾,有多少匹配多少print match #[‘dog‘, ‘dog‘]
#使用 mathch.group 分組使用(),分組和不分組匹配的"大子串"都是一樣,但是分組之後,可以對這些子組做單獨處理。
contactInfo = ‘Doe, John: 555-1212‘match=re.search(r‘\w+, \w+: \S+‘, contactInfo)print match.group(0) #Doe, John: 555-1212match = re.search(r‘(\w+), (\w+): (\S+)‘, contactInfo)print match.group(0) #Doe, John: 555-1212,第0組表示匹配的"大子串",滿足全部條件print match.group(1) #Doeprint match.group(2) #Johnprint match.group(3) #555-1212
#當一個Regex有很多分組的時候,通過組的出現次序來定位就會變的不現實。Python還允許你通過下面的語句來指定一個組名:
match = re.search(r‘(?P<last>\w+), (?P<first>\w+): (?P<phone>\S+)‘, contactInfo)print match.group(‘last‘) #Doeprint match.group(‘first‘) #Johnprint match.group(‘phone‘) #555-1212
#儘管findall()方法不返回分組對象,它也可以使用分組。類似的,findall()方法將返回一個元組的集合,其中每個元組中的第N個元素對應了Regex中的第N個分組。
match=re.findall(r‘\w+, \w+: \S+‘, contactInfo)print match #[‘Doe, John: 555-1212‘]
match=re.findall(r‘(\w+), (\w+): (\S+)‘, contactInfo)print match #[(‘Doe‘, ‘John‘, ‘555-1212‘)]
Python開發應用-正則表達進行排序搜尋