Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a group and match in .NET's RegEx?

Tags:

.net

regex

What is the difference between a Group and a Match in .NET's RegEx?

like image 483
Guy Avatar asked Aug 26 '08 22:08

Guy


2 Answers

A Match is an object that indicates a particular regular expression matched (a portion of) the target text. A Group indicates a portion of a match, if the original regular expression contained group markers (basically a pattern in parentheses). For example, with the following code:

string text = "One car red car blue car";
string pat = @"(\w+)\s+(car)";
Match m = r.Match(text);

m would be match object that contains two groups - group 1, from (\w+), and that captured "One", and group 2 (from (car)) that matched, well, "car".

like image 149
Blair Conrad Avatar answered Sep 22 '22 04:09

Blair Conrad


A Match is a part of a string that matches the regular expression, and there could therefore be multiple matches within a string.

Inside a Match you can define groups, either anonymous or named, to make it easier to split up a match. A simple example is to create a regex to search for URLs, and then use groups inside to find the protocol (http), domain (www.web.com), path (/lol/cats.html) and arguments and what not.

// Example I made up on the spot, probably doesn't work very well
"(?<protocol>\w+)://(?<domain>[^/]+)(?<path>/[^?])"

A single pattern can be found multiple times inside a string, as I said, so if you use Regex.Matches(string text) you will get back multiple matches, each consisting of zero, one or more groups.

Those named groups can be found by either indexing by number, or with a string. The example above can be used like this:

Match match = pattern.Match(urls);
if (!match.Success) 
    continue;
string protocol = match.Groups["protocol"].Value;
string domain = match.Groups[1].Value;

To make things even more interesting, one group could be matched multiple times, but then I recommend start reading the documentation.

You can also use groups to generate back references, and to do partial search and replace, but read more of that on MSDN.

like image 34
Mats Fredriksson Avatar answered Sep 22 '22 04:09

Mats Fredriksson