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.

Building Regular Expressions ❘ 475<br />

Parentheses create groups. For example, consider the expression (\w)\1. The parentheses create a<br />

numbered group that in this example matches a single word character. Later in the expression, the<br />

text \1 refers to group number 1. That means this regular expression matches a word character followed<br />

by itself. If the string is “book,” then this pattern would match the “oo” in the middle.<br />

Group Indexes<br />

In regular expressions, numbered groups are numbered starting at 1, not 0.<br />

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

common are numbered and named groups.<br />

To create a numbered group, simply enclose a subexpression in parentheses as shown in the previous<br />

example.<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.<br />

To use a named group in a regular expression, use the syntax \k.<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. For example, the expression \d{3} matches any digit exactly 3 times. The following table<br />

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<br />

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

the BOO in BOOK. The pattern BO+ also matches a B character followed by 1 or more Os, but it<br />

matches as few Os as possible, so it would match only the BO in BOOK.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!