XML technologies / Regular expressions / .NET / Objects in detail / regex objects in use

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

Creating a Regex object alone is hardly useful; it should also be applied.

RegexObj.IsMatch(Suchtext)                  Typ des Rückgabewerts: Boolean
RegexObj.IsMatch(Suchtext, Offset)

The IsMatch method applies the object’s regex to Suchtext and returns a simple Boolean value indicating success or failure. For example:

Dim R as RegexObj = New Regex("^\s*$")
   ...
If R.IsMatch(Zeile) Then
   ' Leerzeile ...
      ...
Endif

If an integer Offset is supplied, searching begins only at that position in the subject text.

RegexObj.Match(Suchtext)                        Typ des Rückgabewerts: Match-Objekt
RegexObj.Match(Suchtext, Offset)
RegexObj.Match(Suchtext, Offset, Maxlänge)

The Match method applies the object’s regex to the subject and creates a Match object containing all results, such as success status and captured text, which can then be queried. That object can also initiate a search for the next match with the same regex in the same string. Details of the Match object follow in Using Match objects.

If an integer Offset is supplied, searching begins only at that position in the subject text.

If the argument Maxlänge is supplied, the search does not really cover Suchtext, but a substring of length Maxlänge starting at Offset. Characters before and after it are ignored. Thus, ˹^˼ matches at position Offset in the original subject, and ˹$˼ after a further Maxlänge characters. Even lookaround cannot see the preceding or following characters. This differs greatly from supplying only Offset, which affects only where the transmission starts the regex engine, while the engine still sees the entire subject text.

This small table illustrates the meaning of Offset and Maxlänge:

 

Results with the regex…

Method call

˹\d\d˼

˹^\d\d˼

˹^\d\d$˼

RegexObj.Match("May 16, 1998")

Match ›16‹

No match

No match

RegexObj.Match("May 16, 1998", 9)

Match ›99‹

No match

No match

RegexObj.Match("May 16, 1998", 9, 2)

Match ›99‹

Match ›99‹

Match ›99‹

RegexObj.Matches(Suchtext)               Typ des Rückgabewerts: MatchCollection
RegexObj.Matches(Suchtext, Offset)

The Matches method closely resembles Match, but returns a collection of Match objects corresponding to every regex match in the subject, whereas Match returns an object for just the first or sole match. The returned object has type MatchCollection.

After setting up this Regex object and subject:

Dim R as New Regex("\w+")
Dim Suchtext as String = "ein paar Worte"

this code

Dim AlleTreffer as MatchCollection = R.Matches(Suchtext)
Dim I as Integer
For I = 0 to AlleTreffer.Count - 1
    Dim MatchObj as Match = AlleTreffer.Item(I)
    Console.WriteLine("Treffer: " & MatchObj.Value)
Next

produces the following output:

 Treffer: ein
 Treffer: paar
 Treffer: Worte 

The following example does exactly the same thing, showing that the MatchCollection object is optional:

Dim MatchObj as Match
For Each MatchObj in R.Matches(Suchtext)
    Console.WriteLine("Treffer: " & MatchObj.Value)
Next

For comparison, the same task using a single Match object and the NextMatch method, rather than Matches:

Dim MatchObj as Match = R.Match(Suchtext)
While MatchObj.Success
    Console.WriteLine("Treffer: " & MatchObj.Value)
    MatchObj = MatchObj.NextMatch()
End While

RegexObj.Replace(Suchtext, Ersatztext)                  Typ des Rückgabewerts: String
RegexObj.Replace(Suchtext, Ersatztext, Anzahl)
RegexObj.Replace(Suchtext, Ersatztext, Anzahl, Offset)

For “searching and replacing”, .NET uses the Replace method. It applies the Regex object’s regex to the subject and returns a possibly modified copy of that string instead of a Match object. What gets replaced depends on the Ersatztext argument.

This Ersatztext argument is overloaded: it may be a string or a MatchEvaluator delegate. Strings are interpreted according to the rules in the following box. This example encloses capitalized words in <B>...</B>:

Dim R_GrossAnf as New Regex("\b[A-Z]\w*")
   ...
Text = R_GrossAnf.Replace(Text, "<B>$0</B>")

 

Special dollar sequences in replacement text

The methods Regex.Replace and Match.Result have a replacement-text argument interpreted specially. Its Perl-inspired dollar sequences are replaced by text found during matching:

Sequence

Replaced with…

$&

the matched text, also $0.

$1, $2, ..

text matched by the corresponding capturing group

${Name}

text matched by the corresponding named group

$`

text from the subject before the current match

$'

text from the subject after the current match

$$

a single dollar sign

$

the entire original subject string

$+

(see text)

The sequence $+ is fairly useless in this implementation. It was probably intended to imitate Perl’s variable $+, which is genuinely useful and returns the text from the last, highest-numbered group that participated in the match. (See Matching an HTML link for an example.) .NET, however, simply returns text from the highest-numbered group whether or not it participated in the match. This sequence is especially useless if named capturing groups are added to ordinary ones, since they are numbered differently (see Named capturing groups).

All other dollar combinations in replacement text have no special meaning and remain unchanged.

If an Anzahl is supplied, it limits the number of replacements; normally, every match is replaced. To replace only the first match, supply Anzahl 1. If only one match is possible, specifying that count may improve efficiency by avoiding an futile search for further matches. A Anzahl of -1 is equivalent to omitting the Anzahl argument: all matches are replaced.

If an integer Offset is supplied, the regex starts that many characters after the subject’s beginning; skipped characters are copied unchanged into the result.

This example replaces every whitespace sequence with a single space:

Dim WS_Seq as New Regex("\s+")
   ...
Suchtext = WS_Seq.Replace(Suchtext, " ")

This changes the string ›viel● ● ● ● ● leerer● ● ● ● ● Raum‹ into ›viel● leerer● Raum‹. The following example does the same, but leaves leading whitespace untouched:

Dim WS_Seq  as New Regex("\s+")
Dim WS_vorn as New Regex("^\s+")
   ...
Suchtext = WS_Seq.Replace(Suchtext, " ", -1, WS_vorn.Match(Suchtext).Length)

This turns ›●●●●viel●●●leerer●●●●●Raum‹ into ›●●●●viel●leerer●Raum‹.

The example uses the match length of the WS_vorn regex as the offset for the Replace method. Before searching and replacing, it skips as many characters as there are leading whitespace characters. This exploits a useful property of a Match object: even when no match is found with WS_vorn.Match(Suchtext), the Length property has a defined value, zero. Even after failure, that value is exactly what we need for Offset to apply WS_Seq to the entire subject.

 

Using replacement delegates

The Ersatztext argument need not be a string; it can be a delegate , essentially a function pointer. The delegate function is called after matching and produces the replacement text. Since it can do anything, this is a powerful mechanism.

The delegate has type MatchEvaluator and is called once per match. Its target function should accept a Match object as its parameter and return a string to use as replacement text.

For comparison, these two snippets give the same result:

Suchtext = R.Replace(Suchtext, "<<$&>>"))

Function MatchFunc(ByVal M as Match) as String
    return M.Result("<<$&>>")
End Function
Dim Evaluator as MatchEvaluator = New MatchEvaluator(AddressOf MatchFunc)
   ...
Suchtext = R.Replace(Suchtext, Evaluator)

Both enclose the match in <<...>>. A delegate can use arbitrarily complex code to compute the replacement text. In the next example, the function converts Celsius temperatures to Fahrenheit:

Function MatchFunc(ByVal M as Match) as String
    'Temperatur als Zahl aus $1 herausholen, dann in Fahrenheit umrechnen.
    Dim Celsius    as Double = Double.Parse(M.Groups(1).Value)
    Dim Fahrenheit as Double = Celsius * 9/5 + 32
    Return Fahrenheit & "F" 'Ein »F« anhängen und zurückgeben.
End Function
Dim Evaluator as MatchEvaluator = New MatchEvaluator(AddressOf MatchFunc)
   ...
Dim R_Temp as Regex = New Regex("(\d+)C\b", RegexOptions.IgnoreCase)
Suchtext = R_Temp.Replace(Suchtext, Evaluator)

If the subject is ›Temperatur ist 37C.‹, it is replaced with ›Temperatur ist 98.6F.‹.

RegexObj.Split(Suchtext) RegexObj.Split(Suchtext, Anzahl) RegexObj.Split(Suchtext, Anzahl, Offset)

Return type: array of String

The Split method applies the object’s regex to Suchtext and returns an array of text fragments lying between matches in the subject. A simple example:

Dim R as New Regex("\.")
Dim Teile as String() = R.Split("209.204.146.22")

The method call R.Split returns an array of four strings: ›209‹, ›204‹, ›146‹, and ›22 ‹, separated in the subject by matches, the three periods.

If an Anzahl is supplied, at most that many fragments are returned, unless the regex contains capturing parentheses, discussed shortly. Without Anzahl , as many fragments as possible are returned. If a Anzahl is supplied, the engine may stop before finding all matches. If so, the last returned element receives the subject’s entire remainder:

Dim R as New Regex("\.")
Dim Teile as String() = R.Split("209.204.146.22", 2)

This time, Teile receives only two strings: ›209‹ and ›204.146.22‹.

If an integer Offset is supplied, the regex starts that many characters after the subject’s beginning. Skipped characters become part of the first returned element, unless RegexOptions.RightToLeft is used, when they become part of the last element.

 

Using Split with capturing parentheses

When capturing parentheses of any kind are used, extra elements are normally inserted in the returned array. Exceptions are discussed shortly. For example, to break strings such as ›2006-12-31‹ or ›04/12/2007‹ into components, one could split with ˹[-/]˼:

Dim R as New Regex("[-/]")
Dim Teile as String() = R.Split(IrgendeinDatum)

This gives a list of three numbers represented as strings. If we use capturing parentheses and the regex ˹([-/,])˼, we get five strings instead.

If IrgendeinDatum contains ›2006-12-31‹, those elements are ›2006‹, ›-‹, ›12‹, ›-‹, and ›31‹. The extra ›-‹ elements come from the capturing parentheses and correspond to the $1 of each match.

With multiple capturing groups, an extra element is created for each in the usual numeric order: named groups follow ordinary captures (see Named capturing groups).

Split works reliably with capturing parentheses as long as every group participates in the match. Otherwise, the tested .NET regex implementation has a bug: when a group does not participate, no extra element is returned for it or for any higher-numbered group.

Suppose, in a somewhat contrived example, you want to split on a comma with optional surrounding whitespace, and include any matched whitespace in the returned array. The regex ˹(\s+)?, (\s+)?˼ does this. Using Split with this regex on ›dies● , ●●das‹ returns four strings: ›dies‹, ›●‹, ›●●‹, and ›das‹. But with the subject ›dies, ●das‹, the first group does not participate. Because of the bug, no element is returned for the space matched by the second group either. Only two strings are returned: ›dies‹ and ›das‹. Since one cannot predict which groups will participate, this feature is hardly useful in its current form.

This particular example could avoid the problem with ˹(\s*),(\s*)˼: both groups then participate, even if they capture empty strings. More complicated regexes cannot always be rewritten so easily.

RegexObj.GetGroupNames() RegexObj.GetGroupNumbers() RegexObj.GroupNameFromNumber(Zahl) RegexObj.GroupNumberFromName(Name)

These methods provide the numbers and, for named groups, names of capturing parentheses in the regex. They concern no particular search, only group numbering and names in the regex. The following box uses them in an example program.

 

Querying information about a Regex object

This program prints all known information about the Regex object in R:

'Informationen über das Regex-Objekt in R ausgeben.
Console.WriteLine("Regex: " & R.ToString())
Console.WriteLine("Optionen: " & R.Options)

If R.RightToLeft
   Console.WriteLine("Von rechts nach links.")
Else
   Console.WriteLine("Von links nach rechts.")
End If
Dim S as String
For Each S in R.GetGroupNames()
    Console.WriteLine("Name """ & S & """ ist Nr. " & R.GroupNumberFromName(S))
Next
Console.WriteLine("---")
Dim I as Integer
For Each I in R.GetGroupNumbers()
    Console.WriteLine("Nr. " & I & " hat den Namen """ & _
                      R.GroupNameFromNumber(I) & """")
Next
Das Programm wird mit zwei verschiedenen Regex-Objekten ausgeführt:
New Regex("^(\w+)://([^/]+)(/\S*)")
New Regex("^(?<proto>\w+)://(?<host>[^/]+)(?<page>/\S*)",
          RegexOptions.Compiled)

The program runs with two different Regex objects:

New Regex("^(\w+)://([^/]+)(/\S*)")

New Regex("^(?<proto>\w+)://(?<host>[^/]+)(?<page>/\S*)", RegexOptions.Compiled)</page></host></proto>

It produces the following output; the regex on the right is truncated to save space:

Regex: ^(\w+)://([^/]+)(/\S*) Optionen: 0 Von links nach rechts. Name "0" ist Nr. 0 Name "1" ist Nr. 1 Name "2" ist Nr. 2 Name "3" ist Nr. 3 --- Nr. 0 hat den Namen "0" Nr. 1 hat den Namen "1" Nr. 2 hat den Namen "2" Nr. 3 hat den Namen "3"

Regex: ^(?<proto>\w+)://(?<host>[^/]+)... Optionen: 8 Von rechts nach links. Name "0" ist Nr. 0 Name "proto" ist Nr. 1 Name "host" ist Nr. 2 Name "page" ist Nr. 3 --- Nr. 0 hat den Namen "0" Nr. 1 hat den Namen "proto" Nr. 2 hat den Namen "host" Nr. 3 hat den Namen "page"

RegexObj.ToString() RegexObj.RightToLeft RegexObj.Options

These methods and properties describe the Regex object rather than the regex string. The ToString() method recreates the regex’s string representation from the object. The property RightToLeft indicates whether the object was constructed with the option RegexOptions.RightToLeft. The property Options returns all options used to construct the regex, encoded with OR into one numeric value:

0

None

16

Singleline

1

IgnoreCase

32

IgnorePatternWhitespace

2

Multiline

64

RightToLeft

4

ExplicitCapture

8

Compiled

256

ECMAScript

The missing value 128 is an internal Microsoft debugging option excluded from the shipped product.

The preceding box, Querying information about a Regex object, illustrates these methods with an example.

  

 

 

 

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