match class : Group(int) method

Description

Gets a substring that matches the regular expression group selected by the index.

Syntax

matchInstance.Group(int index)

Arguments

ClassNameDescription
intindexA index.

Return value

ClassDescription
stringA substring that matches the regular expression group selected by the index.

Sample code

1:

regex pattern = new regex("(\d)(\d)"); // There are groups in the regular expression.

2:

match firstMatch= pattern.MatchM("ww1245cc66"); // It matches to "12".

3:

int count = firstMatch.GroupCount; // The GroupCount is 3. "12", "1", and "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"); // There is no group in the regular expression.

9:

firstMatch= pattern.MatchM("ww1245cc66"); // It matches to "12".

10:

count = firstMatch.GroupCount; // The GroupCount is 1. The matched substring is also group.

11:

resultStr = firstMatch.Group(0); // "12"

12:

// ---------------------------------------------------------------------------------

13:

firstMatch= pattern.MatchM("wwwwwww"); // It does not match.

14:

count = firstMatch.GroupCount; // Still, the GroupCount is 1.

15:

resultStr = firstMatch.Group(0); // ""

Notes

It's a wrapper of the System.Text.RegularExpressions.Match.Groups property.

The index is 0-based.


The result of matchInstance.Group (0) is always an entire substring.

If the match is successful, the entire matched substring is also recognized as a group, so executing matchInstance.Group (0) will return the entire substring.

If the match is failure, there is no matched substring, so executing matchInstance.Group (0) will return an empty string.

Links for reference

Copyright © Cooker All rights reserved.