C # use regular expression instances

Source: Internet
Author: User

A regular expression can be considered as a powerful wildcard (Universal matching symbol ). Most people should be familiar with wildcards. For example, when we see an expression such as "Sams", any string starting with SAMs in a text string can match this expression. Regular Expressions provide a matching mechanism that is more powerful than such wildcards, more complex control rules, and more functional.

This article will give an overview of the classes provided by the. NET Framework that support regular expressions. For more information about regular expressions, see regular expression pocket reference (O 'Reilly media press, ISBN: 05960020.x) or mastering regular expressions. 2nd edition (O 'Reilly media press, ISBN: 0596002890) and other books. They teach you how to create regular expressions and provide a list of the most common regular expressions.

Input confirmation

One of the most important purposes of a regular expression is to check whether the text of an input conforms to a predefined format. For example, a string that can be used as a password usually follows certain mandatory rules to make it difficult to crack the password string. These rules are often defined as regular expressions. Regular Expressions are often used to confirm some simple input, such as confirming the email address and phone number.

The RegEx class is a key class in the. NET Framework that processes regular expressions. The RegEx class contains a static method named ismatch, which returns a Boolean value indicating whether the specified input string matches a given regular expression.

The followingCodeA common regular expression is used to test whether an email address is valid:

String emailpattern =
@ "^ ([\ W-\.] +) @ (\ [0-9] {1, 3 }\. [0-9] {1, 3 }\. [0-9] {1, 3 }\.) | [CCC]
([\ W-] + \.) +) ([A-Za-Z] {2, 4} | [0-9] {1, 3}) (\]?) $ ";

Console. Write ("enter an e-mail address :");
String emailinput = console. Readline ();
Bool match = RegEx. ismatch (emailinput, emailpattern );
If (MATCH)
Console. writeline ("e-mail address is valid .");
Else
Console. writeline ("supplied input is not a valid e-mail address .");

Do not worry about whether the above regular expression is meaningful. The basic idea behind the email mode is that it must contain some characters, followed by a @ tag, followed by ". "followed by some character combinations,". it must contain at least two characters. You can tryProgramAnd observe the program execution results. It does not matter even if you do not understand the meaning of the regular expression itself. As long as you know that there is a regular expression tool and it can be used to confirm the input, it will be very helpful for you to write the application.

Extract data from input

Another common purpose of regular expressions is to analyze text and extract data (group matching) from user input ).

The Regular Expression in C # contains a unique feature called group. You can assign an identifier name to a specific segment in a regular expression. When the match () method is called to compare the mode and input data, the comparison result is actually a string that is split by group to be matched, this allows you to extract the matching parts from the input.

For example, we can create a group named username in the previous example and use it to extract all the symbol strings located before @ from an email address. In this way, you can use the name group in the regular expression to extract user name information when performing the matching.

The following code example shows how to extract the protocol name and port number from the URL address output by the user on the console. A good feature of regular expressions is that they constitute a language, which is similar to C, C ++, C #, or any other language.Programming LanguageNo dependency. This makes it easy for us to borrow some common regular expressions from Internet or reference application cases. For example, the regular expression in the following routine is borrowed from an example in msdn:

String urlpattern = @ "^ (? <Proto> \ W +): // [^/] +? (? <Port>: \ D + )? /";
Console. writeline ();
Console. Write ("enter a URL for data parsing :");
String url = console. Readline ();
RegEx urlexpression = new RegEx (urlpattern, regexoptions. Compiled );
Match urlmatch = urlexpression. Match (URL );
Console. writeline ("the protocol you entered was" +
Urlmatch. Groups ["Proto"]. value );
Console. writeline ("the port number you entered was" +
Urlmatch. Groups ["Port"]. value );

When running the above routine, if you enter a URL without a port number for it, you will notice that the program does not enter any group of matching values. This is because the input text does not match the regular expression at all. When the input does not match the regular expression, it is clear that no named group can be used to extract meaningful data. If you enter a URL with a port number and matching the regular expression for the preceding example, the output of the program is as follows:

Enter a URL for data parsing: http://server.com: 2100/home. aspx
The protocol you entered was HTTP
The port number you entered was: 2100

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.