learn-Regular Expressions

来源:互联网 发布:游族网络垃圾广告 编辑:程序博客网 时间:2024/05/22 11:50

 

I'm sure you are familiar with the use of "wildcard" characters for pattern matching. For example, if you want to find all the Microsoft Word files in a Windows directory, you search for "*.doc", knowing that the asterisk is interpreted as a wildcard that can match any sequence of characters. Regular expressions are just an elaborate extension of this capability.

In writing programs or web pages that manipulate text, it is frequently necessary to locate strings that match complex patterns. Regular expressions were invented to describe such patterns. Thus, a regular expression is just a shorthand code for a pattern. For example, the pattern "/w+" is a concise way to say "match any non-null strings of alphanumeric characters". The .NET framework provides a powerful class library that makes it easy to include regular expressions in your applications. With this library, you can readily search and replace text, decode complex headers, parse languages, or validate text.

Suppose your web page collects a customer's seven-digit phone number and you want to verify that the phone number is in the correct format, "xxx-xxxx", where each "x" is a digit. The following expression will search through text looking for such a string:

4. /b/d/d/d-/d/d/d/d Find seven-digit phone number

Each "/d" means "match any single digit". The "-" has no special meaning and is interpreted literally, matching a hyphen. To avoid the annoying repetition, we can use a shorthand notation that means the same thing:

5. /b/d{3}-/d{4} Find seven-digit phone number a better way

The "{3}" following the "/d" means "repeat the preceding character three times

原创粉丝点击