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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

480 ❘ CHAPTER 21 Regular Expressions<br />

{<br />

}<br />

try<br />

{<br />

if (Regex.IsMatch(inputTextBox.Text, patternTextBox.Text))<br />

resultLabel.Text = "Match";<br />

else<br />

resultLabel.Text = "No match";<br />

}<br />

catch (Exception ex)<br />

{<br />

resultLabel.Text = ex.Message;<br />

}<br />

The code passes the Regex.IsMatch method the string to validate and the regular expression. The<br />

method returns true if the string satisfies the expression. The program then displays an appropriate<br />

message in resultLabel.<br />

This example uses a try catch block to protect itself from improperly formed regular expressions.<br />

For example, suppose you want to use the expression (.)\1 to detect repeated characters. At one<br />

point while you’re typing you will have entered just (, which is not a valid regular expression.<br />

Finding Matches<br />

The MatchPattern example program described in the preceding<br />

section determines whether a string satisfies a regular expression.<br />

For example, it can use the pattern (.)\1 to verify that the string<br />

bookkeeper contains a double letter. However, that program<br />

won’t tell you where the double letter is. In this example, bookkeeper<br />

contains three double letters: oo, kk, and ee.<br />

The Regex class’s Matches method can give you information<br />

about places where a string matches a regular expression. The<br />

FindMatches example program, which is available for download<br />

and shown in Figure 21-2, displays the parts of a string that<br />

match a pattern.<br />

The FindMatches program uses the following code to locate matches.<br />

// Display matches.<br />

private void FindMatches()<br />

{<br />

try<br />

{<br />

// Make the regex object.<br />

Regex regex = new Regex(patternTextBox.Text);<br />

// Find the matches.<br />

string matches = "";<br />

foreach (Match match in regex.Matches(inputTextBox.Text))<br />

{<br />

Figure 21-2: The FindMatches<br />

example program finds the parts<br />

of a string that match a pattern.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!