XML technologies / Regular expressions / .NET / The .NET regex dialect / Further notes on the .NET dialect

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

Some features deserve more discussion than a mere item in the preceding list.

 

Named capturing groups

In .NET, parentheses can be given a name, using the syntax ˹(?<Name>...)˼ or ˹(?'Name'...)˼ (see Named subexpressions). Both forms do exactly the same thing. I feel that the angle-bracket form is more common, so that is the syntax I use.

Backreferences within the regex to such groups use the construct ˹\k<Name>˼ or ˹\k'Name'˼.

After matching, once a Match object has been created (the .NET object model is discussed in The .NET object model: overview ), text captured by named parentheses is accessible through the Groups(Name) property of the Match object. (In C#, this is Groups[Name].)

In substitution replacement text (see the box Special dollar sequences in replacement text), the same text can be accessed with the sequence ${Name}.

Sometimes it is useful to refer by number even to groups that have names. Named groups are numbered after the ordinary groups:

˹(1\w)1(3?<num>\d+)3(2\s+)2˼

Thus, the sequence of digits matched by ˹\d+˼ in this example can be referred to as either Groups("Num") or Groups(3). This is one and the same group; it simply has two names.

 

An unfortunate consequence

Mixing ordinary and named capturing parentheses is discouraged, but if it cannot be avoided, you should be aware of the consequences. The numbering order matters when the regex is used with Split (see Using Split with capturing parentheses), or when ›$+‹ is used in replacement text (see the box Special dollar sequences in replacement text).

 

Conditional expressions

The condition in a ˹(? if then|else)˼ (see Conditional regular expressions) can be any lookaround, a capturing group’s number, or a named group’s name. Ordinary text or a regex in the condition is automatically interpreted as positive lookahead: the condition behaves as if the text were enclosed in ˹(?=...)˼. This creates an ambiguity: if the regex has no group named ›Num‹ (that is, no ˹(?<Num>...)˼), the condition in ˹...(?(Num)then|else)...˼ is interpreted as positive lookahead, becoming ˹(?=Num)˼. If such a group does exist, however, its contents are interpreted as the condition: if the group named ›Num‹ has matched, the if expression is true.

I can only recommend not relying on this automatic lookahead. An explicit lookahead using ˹(?=...)˼ makes the intention clearer to readers and avoids unpleasant surprises if conditional-group semantics change.

 

Optimized expressions with Compiled

In earlier chapters, I used “compilation” for the entire process of checking the regex’s character representation and converting it to an internal form suitable for later use. .NET calls that process “parsing”. In .NET, “compiling” instead refers to two kinds of optimization after parsing.

Here are the phases in detail, in increasing order of optimization:

 

Parsing

When a regex first appears in a program, it must be checked for correctness and converted to an internal form suitable for later use. Elsewhere in this book, this process is called compilation (see Compiling the regex).

 

On-the-fly compilation

If the option RegexOptions.Compiled is specified when creating the regex, parsing not only converts it to the usual internal form, but compiles it one step further into MSIL (Microsoft Intermediate Language). This lower-level language can in turn be converted to machine code by a JIT (Just-In-Time) compiler when the regex is applied. This takes time and memory, but the resulting code is faster. We examine whether the extra effort pays off later in this section.

 

Precompiled regular expressions

A Regex object, or several, can be encapsulated in an assembly and stored on disk in a DLL (Dynamically Loaded Library, a dynamically loadable library, also called a shared library). This makes the object generally available to other programs. This process is called compiling to an assembly. See the section “Regex assemblies” for more information.

With RegexOptions.Compiled, costs must be weighed against benefits:

Measure

Without RegexOptions.Compiled

With RegexOptions.Compiled

Startup time

Faster

Slower (60 times)

Memory usage

Low

High (about 5–15 KB per regex)

Matching speed

Not as fast

Up to 10 times faster

Ordinary parsing, without RegexOptions.Compiled, which is required for every new regex anyway, is relatively fast. Even on my old 550 MHz NT machine, I measured 1,500 parses per second, even for relatively complicated expressions. With RegexOptions.Compiled, that dropped to about 25 regexes per second. Each regex also consumes about 10 KB of memory, retained for the program’s entire lifetime and unavailable for other purposes.

In time-critical loops where processing speed is paramount, it certainly makes sense to use RegexOptions.Compiled , particularly for regexes applied to large subject strings. For simple regexes used only occasionally on relatively short strings, the extra effort is hardly worthwhile. The many cases in between are less clear-cut: weigh the pros and cons individually and decide case by case.

In certain cases, it may make sense to save a compiled regex in its own DLL as a precompiled Regex object. This can save memory in the final program, since the entire regex compiler is unnecessary; it also loads the regex faster, since it is ready to use in the DLL. As a side benefit, the regex becomes available to other programs (see the box Creating custom regex libraries with assemblies).

 

Right-to-left matching

Searching “backward” has often been proposed. The biggest problem is deciding exactly what “backward” or “right to left” should mean. Is the regex reversed? Is the subject text reversed? Or is the regex engine applied normally at each position, except that the transmission starts at the end of the subject string and moves one position left toward the beginning on each shift?

A concrete example: ˹\d+˼ is applied “backward” to the string ›123●und●456‹. Ordinary matching finds ›123‹, and intuitively it seems clear that a right-to-left search should find ›456‹. But that cannot happen if the engine behaves as described at the end of the preceding paragraph. It still “looks” right, but the transmission starts it at different positions from right to left. The first attempt with ˹\d+˼ starts at ›...456▵‹ and fails. The transmission starts the second attempt at ›...45▵6‹: to its right, the engine “sees” the ›6‹, which certainly satisfies the requirement ˹\d+˼ . A match is found this time, but it is only the ›6‹.

.NET provides the option RegexOptions.RightToLeft. How exactly does this right-to-left search work? The answer is “Good question!” Its behavior is undocumented, and my tests have not made it clear to me. In many cases, such as this example with ›123●und●456‹, the result is intuitively as expected: ›456‹ is found. But sometimes nothing at all is found, and sometimes a match seemingly inconsistent with the other results.

Depending on the situation, RegexOptions.RightToLeft may do exactly what you want. Nevertheless, use it at your own risk, because its behavior is undefined.

 

Ambiguities with backslash and digits

A backslash followed by a number is either an octal escape or a backreference. In the .NET package, which interpretation applies depends on the option RegexOptions.ECMAScript. To avoid these subtleties, always use the syntax ˹\k<Zahl>˼ for backreferences and always supply a leading zero for octal escapes, such as ˹\08˼. These two notations are always unambiguous and independent of RegexOptions.ECMAScript.

When RegexOptions.ECMAScript is not enabled, backslash sequences from ˹\1˼ through ˹\9˼ are always backreferences, and sequences beginning with 0 are always octal escapes: ˹\012˼ therefore matches ASCII LF. If neither case applies, the sequence is interpreted as a backreference “if that makes sense”, meaning that the regex has at least that many capturing groups. Other sequences in the range \000 to \377 are treated as octal escapes. Thus, ˹\12˼ is interpreted as a backreference if the regex has twelve or more capturing groups.

These rules change when the option RegexOptions.ECMAScript is used.

 

ECMAScript mode

ECMAScript is a standardized version of JavaScript (note: ECMA stands for European Computer Manufacturers Association, a computer standards organization founded in 1960), with its own rules for interpreting and applying regular expressions. .NET regexes can use these rules by specifying the option RegexOptions.ECMAScript when creating the regex object. If ECMAScript means nothing to you and you do not need compatibility with its rules, you can skip this section.

When the option RegexOptions.ECMAScript is enabled, the following applies:

  • The option RegexOptions.ECMAScript can be combined only with these options:

    RegexOptions.IgnoreCase 
    RegexOptions.Multiline 
    RegexOptions.Compiled 
  • \w, \d and \s (and \W, \D and \S) refer only to ASCII characters.

  • Digits following a backslash are interpreted as a backreference whenever possible, rather than as an octal escape. In ˹(...)\10˼, for example, ˹\10˼ is interpreted as a backreference to the first capturing group followed by a literal ›0‹.

  

 

 

 

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