03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

838 ❘ Appendix T Regular Expressions<br />

Grouping Constructs<br />

Grouping constructs let you define capture groups within matching pieces of a string. Parentheses<br />

create groups. There are several kinds of groups, some of which are fairly specialized and confusing.<br />

The two most common are numbered and named groups.<br />

To create a numbered group, simply enclose a subexpression in parentheses as in (\w)\1. The \w<br />

in this expression matches a single word character. The parentheses mean this character is in the<br />

first numbered group. The \1 that follows matches whatever is in group 1, in this case a single word<br />

character. That means this expression matches a single word character that appears twice.<br />

To create a named group, use the syntax (subexpression) where name is the name you<br />

want to assign to the group and subexpression is a subexpression. Use the syntax \k to<br />

refer to a named group.<br />

For example, the expression (\w)\k is equivalent to the previous expression<br />

(\w)\1 except the group is named twice.<br />

Quantifiers<br />

A quantifier makes the regular expression engine match the previous element a certain number of<br />

times. The following table describes regular expression quantifiers.<br />

Quantifier<br />

Meaning<br />

* Matches the previous element 0 or more times<br />

+ Matches the previous element 1 or more times<br />

Matches the previous element 0 or 1 times<br />

{n}<br />

{n,}<br />

{n,m}<br />

Matches the previous element exactly n times<br />

Matches the previous element n or more times<br />

Matches the previous element between n and m times (inclusive)<br />

If you follow one of these with , the pattern matches the preceding expression as few times as possible.<br />

For example, the pattern BO+ matches B followed by 1 or more Os, so it would match the BOO<br />

in BOOK. The pattern BO+ also matches B followed by 1 or more Os, but it matches as few Os as possible,<br />

so it would match only the BO in BOOK.<br />

Alternation Constructs<br />

An alternation construct uses the | character to allow a pattern to match either of two subexpressions.<br />

For example, the expression ^(true|yes)$ matches either true or yes.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!