match クラス : Group(int) メソッド
説明
インデックスによって選択される正規表現グループに一致する部分文字列を取得します。
構文
matchInstance.Group(int index)
引数
| クラス | 名前 | 説明 |
| int | index | インデックス。 |
返り値
| クラス | 説明 |
| string | インデックスによって選択される正規表現グループに一致する部分文字列。 |
サンプルコード
| 1: | regex pattern = new regex("(\d)(\d)"); // 正規表現にグループがある。 |
| 2: | match firstMatch= pattern.MatchM("ww1245cc66"); // "12"に一致。 |
| 3: | int count = firstMatch.GroupCount; // グループ数は、3。"12", "1", "2" |
| 4: | string resultStr = firstMatch.Group(0); // "12" |
| 5: | resultStr = firstMatch.Group(1); // "1" |
| 6: | resultStr = firstMatch.Group(2); // "2" |
| 7: | // --------------------------------------------------------------------------------- |
| 8: | pattern = new regex("\d\d"); // 正規表現にグループが無い。 |
| 9: | firstMatch= pattern.MatchM("ww1245cc66"); // "12"に一致。 |
| 10: | count = firstMatch.GroupCount; // グループ数は、1。一致した部分文字列全体もグループ |
| 11: | resultStr = firstMatch.Group(0); // "12" |
| 12: | // --------------------------------------------------------------------------------- |
| 13: | firstMatch= pattern.MatchM("wwwwwww"); // 一致しない。 |
| 14: | count = firstMatch.GroupCount; // グループ数は、1。 |
| 15: | resultStr = firstMatch.Group(0); // "" |
注意
これは、System.Text.RegularExpressions.Match.Groups プロパティのラッパーです。
インデックスは、0 ベースです。
matchInstance.Group(0) の結果は、常に部分文字列全体です。
一致に成功した場合、一致した部分文字列全体も一つのグループとして認識されるので、matchInstance.Group(0) を実行すると部分文字列全体が返ります。
一致が失敗した場合、一致した部分文字列全体が無いので、matchInstance.Group(0) を実行すると空文字列が返ります。


