Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Base Types
 Alternation Constructs

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
.NET Framework Developer's Guide 
Alternation Constructs 

The following table lists special characters that modify a regular expression to allow either/or matching.

Alternation construct Definition

|

Matches any one of the terms separated by the | (vertical bar) character; for example, cat|dog|tiger. The leftmost successful match wins.

(?(expression)yes|no)

Matches the "yes" part if the expression matches at this point; otherwise, matches the "no" part. The "no" part can be omitted. The expression can be any valid subexpression, but it is turned into a zero-width assertion, so this syntax is equivalent to (?(?=expression)yes|no). Note that if the expression is the name of a named group or a capturing group number, the alternation construct is interpreted as a capture test (described in the next row of this table). To avoid confusion in these cases, you can spell out the inside (?=expression) explicitly.

(?(name)yes|no)

Matches the "yes" part if the named capture string has a match; otherwise, matches the "no" part. The "no" part can be omitted. If the given name does not correspond to the name or number of a capturing group used in this expression, the alternation construct is interpreted as an expression test (described in the preceding row of this table).

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Matches include empty groups      Dan Appleman   |   Edit   |   Show History

The (?(name).. alternation uses the Success property of the group to determine if it as a match. This may include matches that contain no data.

Consider the following expression to identify the area code part of a phone number. Say you want to match either (nnn) or nnn- . You might try the following:

(?<agroup>\(?)\d{3}(?(agroup)\)|-)

But this will always match the right paren because the term \(? will always be successful (matching either one left paren, or no left parens).

What you really want is the following:

(?<agroup>\()?d{3}(?(agroup)\)|-)

In this case if a left paren isn't found, the group will not contain a succesful match.

In both cases, a missing left paren will result in an empty group, but in the first case it will count as a successful match and thus the "true" term of the alternation will apply, in the second case it will count as a failed match and thus the "false" term of the alternation will apply.

Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker