C # using regular expression Instances _ Basic application

Source: Internet
Author: User
Tags readline


A regular expression can be viewed as a powerful wildcard character (a universal match symbol). Most people should be familiar with wildcards, for example, when we see an expression such as "SAMS", then any string that starts with SAMS in a text string can match that expression. Regular expressions provide a matching mechanism that is more powerful than this wildcard, more complex control rules, and more functional.

This article will be on. NET Framework provides an overview of classes that support regular expressions. For more information about regular expressions, refer to the Regular Expression Pocket Reference (O ' Reilly Media publishing House, isbn:059600415x) or mastering Regular Expressions, 2nd Edition (O ' Reilly Media Press, isbn:0596002890) and other books. They can teach you how to create regular expressions and provide a list of the most commonly used regular expressions.

Enter confirmation

One of the most important uses of regular expressions is to verify that the text you enter conforms to a predefined format. For example, a string that can be used as a password usually follows certain mandatory rules to make the password string difficult to crack. These rules are often defined as regular expressions. Regular expressions are also often used to perform validation on some simple input, such as confirming an email address and a phone number.

The Regex class is a key class in the. NET Framework that handles regular expressions. The Regex class contains a static method named IsMatch that returns a Boolean value that indicates whether the specified input string matches a given regular expression.

In the following code, a 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.");

Don't worry about whether the regular expression above is meaningful. The basic idea behind the email pattern is that it must contain some characters, then a @ tag, followed by the "." followed by some combination of characters, "." You must have at least two characters after that. You can try to use different text as input in the above program section and observe the results of the program execution. Even if you don't understand the meaning of the regular expression itself, it doesn't matter. As long as you know there is a tool for regular expressions, and it can be used to validate input, this is very helpful for you to write your application.

Extract data from the input

Another common use of regular expressions is to parse the text and extract the data from the user's input (called a group match).

Regular expressions in C # contain a unique feature called a group. With groups, you can assign an identifier name to a specific segment in a regular expression. When the match () method is used to compare the pattern to the input data, the result of the comparison is actually a matching string of symbols that is split by the group, allowing you to extract from the input the parts that match each group.

For example, we could create a group named username in the previous example, and use it to extract from an email address all the symbolic strings that precede the @. Thus, when a match is performed, the named group in the regular expression can be applied to extract the user name information.

Look at the following code example, which shows how to extract both the protocol name and the port number from the user's URL address in the console output. A good feature of a regular expression is that it itself constitutes a language that is not dependent on C, C + +, C #, or any other programming language. This makes it easy to borrow some commonly used regular expressions from the Internet or reference case. 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 is" +
Urlmatch.groups["Proto"]. Value);
Console.WriteLine ("The Port number you entered is" +
urlmatch.groups["Port"]. Value);

When you run the above routine, if you enter a URL with no port number for it, you will notice that the program does not enter any of the group's matching values. This is because the text you enter does not match the regular expression at all. When the input does not match the regular expression, it is obvious that no named group can be used to extract meaningful data. If you enter a URL with a port number and match the regular expression for the preceding routine, the output from the program will look like this:

Enter a URL for data parsing:http://server.com:2100/home.aspx
The Protocol you entered is 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.