1. 程式人生 > >Python 正則表示式的 Match 物件的 group 方法

Python 正則表示式的 Match 物件的 group 方法

用法介紹

match.group([group1, ...])

返回 match 的一個或多個子組。

如果只有唯的一引數,返回單一的子符串;如果有多個引數,結果是對應每一個引數的元素組成的 tuple 。
如果沒有引數, group1 的預設值為 0 (返回整個匹配的字串)。

如果一個 groupN 引數的值為 0 ,對應的返回值為整個匹配的字串;如果引數值在 1 到 99 之間(含),返回對應的括號組匹配的字串。

如果組號引數 (groupN)為負數,或者大於定義在模式中的組的個數,會丟擲一個 IndexError 異常。

如果模式中的某個組沒有匹配(例如:(\w+ )?(\w+ )*

),對應的結果為 None 。

如果模式中的某個組匹配了多次(例如:(\w+ )+(\w+ )*),將返回最後匹配的字串。

Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned.

示例

程式

# coding=utf-8

import re

s = "[this is a book]"
PATTERN = "\[(((\w+)(\s+)?)+)\]"

m = re.search(PATTERN, s, re.DOTALL)
if m:
    for i in range(5):
        print("m.group(%d) => '%s', start = %d, end = %d" % (i, m.group(i), m.start(i), m.end(i)))

    it = re.finditer("(\w+)(\s+)?", m.group(1
)) for match in it: print("m.group(1, 2) => '%s','%s'" % match.group(1, 2))

執行結果

m.group(0) => '[this is a book]', start = 0, end = 16
m.group(1) => 'this is a book', start = 1, end = 15
m.group(2) => 'book', start = 11, end = 15
m.group(3) => 'book', start = 11, end = 15
m.group(4) => ' ', start = 10, end = 11
m.group(1, 2) => 'this',' '
m.group(1, 2) => 'is',' '
m.group(1, 2) => 'a',' '
m.group(1, 2) => 'book','None'

參考