1. 程式人生 > 實用技巧 >正則 re.match & re.search

正則 re.match & re.search

re.match函式

re.match 嘗試從字串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。

語法

re.match(pattern, string, flags=0)
  • pattern :匹配的正則表示式
  • string :要匹配的字串。
  • flags :標誌位,用於控制正則表示式的匹配方式,如:是否區分大小寫,多行匹配等等。參見 : 正則表示式修飾符 - 可選標誌

匹配成功re.match方法返回一個匹配的物件,否則返回None。

我們可以使用group(num) 或 groups() 匹配物件函式來獲取匹配表示式。

  • group(num=0) :匹配的整個表示式的字串,group() 可以一次輸入多個組號,在這種情況下它將返回一個包含那些組所對應值的元組。
  • groups() :返回一個包含所有小組字串的元組,從 1 到 所含的小組號。
1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*- 
3  
4 import re
5 print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配
6 print(re.match('com', 'www.runoob.com'))         # 不在起始位置匹配
案例

輸出結果:

(0, 3)
None
 1 #!/usr/bin/python
 2 import re
 3  
 4 line = "Cats are smarter than dogs
" 5 6 matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) 7 8 if matchObj: 9 print "matchObj.group() : ", matchObj.group() 10 print "matchObj.group(1) : ", matchObj.group(1) 11 print "matchObj.group(2) : ", matchObj.group(2) 12 else: 13 print "No match!!"
案例

輸出結果:

matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter

re.search方法

re.search 掃描整個字串並返回第一個成功的匹配。

語法:

re.search(pattern, string, flags=0)
1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*- 
3  
4 import re
5 print(re.search('www', 'www.runoob.com').span())  # 在起始位置匹配
6 print(re.search('com', 'www.runoob.com').span())         # 不在起始位置匹配
案例

輸出結果:

(0, 3)
(11, 14)
 1 #!/usr/bin/python
 2 import re
 3  
 4 line = "Cats are smarter than dogs";
 5  
 6 searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
 7  
 8 if searchObj:
 9    print "searchObj.group() : ", searchObj.group()
10    print "searchObj.group(1) : ", searchObj.group(1)
11    print "searchObj.group(2) : ", searchObj.group(2)
12 else:
13    print "Nothing found!!"
案例

輸出結果:

searchObj.group() :  Cats are smarter than dogs
searchObj.group(1) :  Cats
searchObj.group(2) :  smarter

re.match與re.search的區別

re.match只匹配字串的開始,如果字串開始不符合正則表示式,則匹配失敗,函式返回None;而re.search匹配整個字串,直到找到一個匹配。

 1 #!/usr/bin/python
 2 import re
 3  
 4 line = "Cats are smarter than dogs";
 5  
 6 matchObj = re.match( r'dogs', line, re.M|re.I)
 7 if matchObj:
 8    print "match --> matchObj.group() : ", matchObj.group()
 9 else:
10    print "No match!!"
11  
12 matchObj = re.search( r'dogs', line, re.M|re.I)
13 if matchObj:
14    print "search --> searchObj.group() : ", matchObj.group()
15 else:
16    print "No match!!"
案例

輸出結果:

No match!!
search --> searchObj.group() :  dogs