記錄正規表達式的 group 擷取字串的順序。
Python 的正規表達式,透過 group() 函式擷取括號框住的內容。
以下是我寫的例子:
執行結果
match: food @123
1: food
2: oo
3: @123
4: 123
tmp = 128
tmp[2] = 3
match: feed
1: feed
2: ee
3: None
4: None
None detected in group(4).
tmp: None
幾個重點
Python 的正規表達式,透過 group() 函式擷取括號框住的內容。
以下是我寫的例子:
import re def main(): string_to_search_1 = "food @123" string_to_search_2 = "feed" pattern = re.compile(r'(f(oo|ee)d)\s*(@(\d+))*') matches = pattern.finditer(string_to_search_1) for match in matches: print "match:", match.group() print "1:", match.group(1) print "2:", match.group(2) print "3:", match.group(3) print "4:", match.group(4) # print "5:", match.group(5) # no such group. tmp = int(match.group(4)) tmp += 5 print "tmp =", tmp tmp = str(match.group(4)) print "tmp[2] =", tmp[2] matches = pattern.finditer(string_to_search_2) for match in matches: print "match:", match.group() print "1:", match.group(1) print "2:", match.group(2) print "3:", match.group(3) # print "4:", match.group(4) # # print "5:", match.group(5) # no such group. if match.group(4) is None: print " None detected in group(4)." tmp = str(match.group(4)) print "tmp:", tmp if(__name__ == "__main__"): main()
執行結果
match: food @123
1: food
2: oo
3: @123
4: 123
tmp = 128
tmp[2] = 3
match: feed
1: feed
2: ee
3: None
4: None
None detected in group(4).
tmp: None
幾個重點
- 在正規表達式內,有幾個括號,就有幾組 group。
- 在 string_to_search_1 內掃描 (f(oo|ee)d) 這個 Pattern,group(1) 會回傳 food,group(2) 回傳 "oo"。先從最外大括號先回傳,其次再回傳內部小括號的字串。
- 回傳的字串可以自由的轉成整數或是取出個別字元。
- 在 string_to_search_2 內,group(3) 跟 group(4) 都回傳 None,因為找不到對應 Pattern。
留言
張貼留言