1. 程式人生 > >【Java正則表示式系列】7 Capturing Groups(匹配組)

【Java正則表示式系列】7 Capturing Groups(匹配組)

上一節中我們在學習Quantifier時候,也考察了和Capturing Groups結合的意義。本節主要對Capturing Groups進行描述一下。

它的意義和用途很簡單,它就是把一組字串當做一個整體來看待,比如 (abc)我們就應該將字串abc看做一個整體。

輸入匹配的字串如果匹配Capturing Groups的正則內容,匹配引擎會將匹配部分的位置和資訊記錄在記憶體中,以便後續backreference的回撥提供上下文環境。

1. 編號

Pattern類java doc中對Capturing Groups根據左括號從左到右進行編號,所以對於((A)(B(C))),則進行如下的標號:
1. ((A)(B(C)))
2. (A)
3. (B(C))
4. (C)

為了瞭解表示式中多個Group,可以通過Matcher.groupCount方法獲取.

這裡存在一個特殊的group, group0, 它代表整個正則表示式,它是不會包含在groupCount返回值裡面的。

對於group的編號我們得認真理解,在Matcher裡面有關很多方法涉及到group number的概念.

public int start(int group): Returns the start index of the subsequence captured by the given group during the previous match operation.

public int end (int group)

: Returns the index of the last character, plus one, of the subsequence captured by the given group during the previous match operation.

public String group (int group): Returns the input subsequence captured by the given group during the previous match operation.

2. backreferences

我們在上面提交到如果capturing groups匹配到,它會將group匹配的結果放到記憶體裡面,可以給backreference進行索引,
下面先通過一個例子進行了解一下:
這裡寫圖片描述

上面就只有一個group, group開始匹配的結果是12,這是因為(\d\d)表示兩個數字,此時,記憶體裡面會記錄group 1的匹配值為12, 接著匹配\1時,這個表示group 1匹配的值,此時,就應該要求接下來的字串也是12,故當前匹配的字串是1212.

下面我們稍微調整一下看看結果:
這裡寫圖片描述

上面的結果也就很明白了。