Python 2.7的手冊中的解釋:html
(?P<name>...)python
Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name. Group names must be valid python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named id in the example below can also be referenced as the numbered group 1.正則表達式
For example, if the pattern is (?P<id>[a-zA-Z_]\w*), the group can be referenced by its name in arguments to methods of match objects, such asm.group('id') or m.end('id'), and also by name in the regular expression itself (using (?P=id)) and replacement text given to .sub() (using \g<id>).express
此處詳細解釋一下上述原文的意思:ide
聲明:此處儘可能稱 group爲「group」,而不翻譯爲 漢字的「組」,以便容易理解和去強化group自己的組的含義。wordpress
1.此處的(?P<name>…),和普通的(?…):學習
【教程】詳解Python正則表達式之: (…) group 分組google
基本相似。區別在於,此處因爲是給此group命名了,因此,後續(同一正則表達式內和搜索後獲得的Match對象中),均可以經過此group的名字而去引用此group。spa
2. group的名字,當前須要是正常的Python標識符,即字母,數字,下劃線等,即,沒有特殊的字符。.net
3.同一正則表達式內,每一個group的組名,是惟一的,不能重複。
4. 雖然此處group內命名了,可是其仍然和普通的
【教程】詳解Python正則表達式之: (…) group 分組
中同樣,能夠經過索引號,即group(1),group(2)等等,去引用對應的group的。
很明顯,按照正則內被命名的group的順序,依次地
group(1)==group(name1)
group(2)==group(name2)
….
下面就整理出示例代碼,用於演示,named group的用法,其中也包括了,相對要複雜一點的:
(1)命了名的group,在當前的正則表達式中,後續被(?P=name)的方式引用;
其中,詳細注意事項,可參考:
【教程】詳解Python正則表達式之: (?P=name) match earlier named group 匹配前面已命名的組
(2)re.sub()中後續經過\g<name>方式被引用。
示例代碼以下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
【總結】
1. 通常多數是經過matched.group(name)的方式去得到對應所查找到的字符串的。
2. 關於匹配以前已經出現的字符串,可使用:
(1)在re.search等中,使用(?P=name);
(2)在re.sub的被替換的字符串中,使用\g<name>的方式得到以前已命名的group的值;