XML technologies / Regular expressions / .NET / Objects in detail / Using Match objects
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Match objects are created by method Match of a Regex object, by static function Regex.Match, discussed shortly, and by method NextMatch of the Match object itself. Each object holds all information about one match of the regex. It has these properties and methods:
MatchObj.Success
Returns a Boolean indicating whether a match was found. On failure, the object is a copy of static object Match.Empty (see Match.Empty).
MatchObj.Value
MatchObj.ToString()
Return the matched text.
MatchObj.Length
Returns the number of characters in the matched text.
MatchObj.Index
Returns the match’s start in the input string as an integer. Characters are counted from zero, so this is the number of characters before the match. This also applies when option RegexOptions.RightToLeft is used.
MatchObj.Groups
This property is a GroupCollection object containing several Group objects. It is an ordinary collection with methods Count and Item, but is usually indexed to access individual Group objects. M.Groups(3) is the Group object for the third capturing group; M.Groups("HostName") is the object for named group ˹(?<HostName>...)˼.
In C#, write M.Groups[3] and M.Groups["HostName"].
Group zero represents the whole match; MatchObj.Groups(0).Value is therefore equivalent to MatchObj.Value.
MatchObj.NextMatch()
Method NextMatch() reapplies the original regex and returns a new Match object representing the next match.
MatchObj.Result(String)
Dollar sequences in the string are processed as described in Special dollar sequences in replacement text. The return value is the modified string. For example:
Dim M as Match = Regex.Match(BeispielString, "\w+")
Console.WriteLine(M.Result("Das erste Wort ist '$&'"))This can, for example, retrieve the text on either side of the match:
M.Result("$`") 'Text aus dem Suchstring links des Treffers.
M.Result("$'") 'Text aus dem Suchstring rechts des Treffers.A line like this is often useful for debugging:
M.Result("[$`<$&>$']"))For a Match object created from regex ˹\d+˼ and input string ‘May 16, 1998’, the output is ‘May <16>, 1998’.
MatchObj.Synchronized()
Returns a Match object identical to the current one but usable in a multithreaded environment.
MatchObj.Captures
Property Captures is rarely used; see Capture objects.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln
back to top