Chapter 19 Working with Regular Expressions

Team Fly 

Page 543

Chapter 19
Working with Regular Expressions

THIS CHAPTER DEALS WITH a classic and very popular topic in computer science, regular expressions. Regular expressions are supported in the .NET Framework by the System.Text.RegularExpressions, which we'll discuss here, along with a few practical examples. Regular expressions are strings that match patterns of text. They consist of characters and digits, some of which have special meaning. The asterisk, for example, means any number of characters and the period means any single character. The expression ''.*" (without the quotes, of course) means any character, any number of times. Regular expressions are not the same as the wildcard characters you use to match file patterns. The expression ".*" has a totally different meaning as a regular expression than it has as a file-matching specification. As a regular expression, it matches an entire line of text, or the entire text.

A regular expression allows you to search for general text patterns, instead of literals. The IndexOf method of the String class searches for a specific string in a longer one. The IndexOf method (the InStr() function works the same way), locates exact instances of the string you specify as argument. When you use regular expressions, you can specify a pattern such as all e-mail addresses or all dollar amounts in the text. If the text contains product codes that have a specific pattern, like XX-NNN-X, where Xs are uppercase letters and Ns are digits, you can locate all product codes in a single sweep through the text with the help of the appropriate regular expression.

Regular expressions are an extremely powerful tool in text processing. The System.Text.RegularExpressions class abstracts a very powerful engine for matching regular expressions against arbitrary text. All you have to do is specify the regular expression and the text to be searched and then call a method to retrieve the matches. The RegularExpressions class makes it very easy to locate any pattern in a text, as long as you can construct the appropriate regular expression. Writing the correct regular expression is not trivial, but this is something you get used to. Besides, a simple search on the Internet will return many regular expressions for common patterns such as e-mail addresses, IP addresses, phone numbers, and so on.

Team Fly 


Visual Basic  .NET Power Tools
Visual Basic .NET Power Tools
ISBN: 0782142427
EAN: 2147483647
Year: 2003
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net