Chapter 21 Regular Expressions
What’s in This Chapter
- Regular expression syntax
- Using regular expressions to detect matches, find matches, and make replacements
- Using regular expressions to parse input
Wrox.com Downloads for This Chapter
Please note that all the code examples for this chapter are available as a part of this chapter’s code download on the book’s website at www.wrox.com/go/csharp5programmersref on the Download Code tab.
Many applications enable the user to type information but the information should match some sort of pattern. For example, the string 784-369 is not a valid phone number and Rod@Stephens@C#Helper.com is not a valid e-mail address.
One approach for validating this kind of input is to use string methods. You could use the string
class’s IndexOf
, LastIndexOf
, Substring
, and other methods to break the input apart and see if the pieces make sense. For all but the simplest situations, however, that would be a huge amount of work.
Regular expressions provide another method for verifying that the user’s input matches a pattern. A regular expression is a string that contains characters that define a pattern. For example, the regular expression ^\d{3}-\d{4}$
represents a pattern that matches three digits followed by a hyphen followed by four more digits as in 123-4567. (This isn’t a great pattern for matching U.S. phone numbers because it enables many invalid combinations such as 111-1111 and 000-0000.)
The .NET Framework includes classes that can use ...
Get C# 5.0 Programmer's Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.