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.

21<br />

Regular Expressions<br />

What’s in This Chapter<br />

➤➤<br />

➤➤<br />

➤➤<br />

Regular expression syntax<br />

Using regular expressions to detect matches, find matches, and<br />

make replacements<br />

Using regular expressions to parse input<br />

Wrox.com Downloads for This Chapter<br />

Please note that all the code examples for this chapter are available as a part of this chapter’s<br />

code download on the book’s website at www.wrox.com/go/csharp5programmersref on the<br />

Download Code tab.<br />

Many applications enable the user to type information but the information should match<br />

some sort of pattern. For example, the string 784-36λ9 is not a valid phone number and<br />

Rod@Stephens@<strong>C#</strong>Helper.com is not a valid e‐mail address.<br />

One approach for validating this kind of input is to use string methods. You could use the string<br />

class’s IndexOf, LastIndexOf, Substring, and other methods to break the input apart and see if<br />

the pieces make sense. For all but the simplest situations, however, that would be a huge amount<br />

of work.<br />

Regular expressions provide another method for verifying that the user’s input matches a<br />

pattern. A regular expression is a string that contains characters that define a pattern. For<br />

example, the regular expression ^\d{3}-\d{4}$ represents a pattern that matches three<br />

digits followed by a hyphen followed by four more digits as in 123-4567. (This isn’t a great<br />

pattern for matching U.S. phone numbers because it enables many invalid combinations such<br />

as 111-1111 and 000-0000.)<br />

The .NET Framework includes classes that can use regular expressions to see if an input string<br />

matches the pattern. They also provide methods for locating patterns within input text and for<br />

making complex substitutions.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!