C # Learning (v)-Regular expressions, etc.

Source: Internet
Author: User

1. Regular expressions

A. What is a regular expression?

When writing a program or Web page that handles strings, there is often a need to find strings that match certain complex rules. Regular expressions are the tools used to describe these rules. In other words, the regular expression is the code that records the text rule. Regular expressions consist of two types of characters, literals (literal value), metacharacters (metacharacters). The literal value is the character you want to match, and the metacharacters are special characters used by regular Expressions , like a command that makes regular expressions function accordingly.

B. Regular expression function instance parsing

  Suppose you look for hi in an English novel , you can use the regular expression hi.

This is almost the simplest regular expression, it can exactly match such a string: two characters, the previous character is H, the latter is I. Typically, a tool that handles regular expressions provides an option to ignore the case, and if this option is selected, it can match any of the four cases of Hi, Hi,hi,hi.

Unfortunately, many words contain the two consecutive characters of Hi, such as him, history, high, and so on. With hi to find, the side of the hi will be found. If we want to find the word hi exactly, we should use \bhi\b. \b is a special code specified by regular expressions (well, some people call it metacharacters, metacharacter), which represents the beginning or end of a word, that is, the boundary of a word. Although English words are usually delimited by spaces, punctuation marks, or line breaks, \b does not match any of these word-delimited characters, it only matches one position .

This is the function of regular expressions, which are used in many text editors to retrieve and replace text that conforms to a pattern.

C. Using regular expressions in C #

The regular expression in . Net is a string representation, this string format is very special, no matter how special, in the C # language seems to be a normal string, what the meaning of the Regex class inside the syntax analysis.

  There are three important methods in C # that correspond to regular expressions.

1) IsMatch () return value is bool type

Format: Regex.IsMatch ("string", "regular expression");

Role: Determine whether a string meets template requirements

For example:bool B =regex.ismatch ("BBBBG", "^b.*g$"), determines whether a string starts with B and ends with a G , can have other characters in the middle, or if True is returned correctly, otherwise else.

2) the match () return value is match type and matches only one

The Matches () return value is the matchcollection collection type, matching all conforming

Format: Match match = Regex.match ("string", "regular expression");

or matchcollection matches= Regex. Matches ("string", "regular expression");

Role:

① extracting a matched substring

② Extraction Group. The subscript of the Groups starts with 1 , and thevalue of match is stored in 0 .

For example:

1Match match = Regex.match ("age=30",@"^(.+)=(.+)$");2 if(match. Success) {3Console.WriteLine (match. groups[0] . Value);//output matched substrings4Console.WriteLine (match. groups[1] . Value);//get the contents of the first group5Console.WriteLine (match. groups[2] . Value);//get the contents of a second group6}
 1  matchcollection matches = regex.matches ( "  October 10, 2010  " , @ " \d+  "   2  for  (i NT  i = 0 ; I < matches. Count; I++)   {  4   Console.WriteLine (matches[i].v Alue);  5 } 

3) Replace () return value is string

1 //Replace all spaces with a single space2 stringstr ="AA AfDs FDS F";3str = Regex.Replace (str,@"\s+"," ");4 Console.WriteLine (str);5 6 stringstr ="Hello "Welcome to" beautiful " China"";7 //Hello "Welcome to" beautiful " China"8 //$ = refers to the first group. The $-a represents the second group. 9 stringstrresult = Regex.Replace (str,""(. +?)"","\ "$1\"");TenConsole.WriteLine (strresult);

Greed and laziness:

When a regular expression contains a qualifier that can accept duplicates, the usual behavior is to match as many characters as possible (in order for the entire expression to be matched). Take this expression as an example: A.*b, which will match the longest string starting with a and ending with B. If you use it to search for Aabab, it will match the entire string aabab. This is called a greedy match.
Sometimes we need more lazy matching, which is to match as few characters as possible. The qualifier given above can be converted to lazy matching mode, just add a question mark after it. So. * is meant to match any number of repetitions, but with minimal repetition in the premise that the entire match succeeds.

2. Async and await keywords for C #

Async and await are introduced in C # 5.0. These two keywords can make it easier for you to write asynchronous code. The await operator applies the execution of a task suspend method to an async method until the task is waiting for completion. The task represents the work in progress.

Cite an example:

1  Public classMyClass2 {3      PublicMyClass ()4     {5Displayvalue ();//There's no blocking .6System.Diagnostics.Debug.WriteLine ("MyClass () End.");7     }8      Publictask<Double> Getvalueasync (DoubleNUM1,Doublenum2)9     {Ten         returnTask.run (() = One         { A              for(inti =0; I <1000000; i++) -             { -NUM1 = NUM1/num2; the             } -             returnNUM1; -         }); -     } +      Public Async voidDisplayvalue () -     { +         Doubleresult =awaitGetvalueasync (1234.5,1.01);//a new thread is opened here to process the Getvalueasync task, and the method immediately returns A         //All code after this is encapsulated as a delegate, which is called when the Getvalueasync task completes. atSystem.Diagnostics.Debug.WriteLine ("Value is:"+result); -     } -}

The ASYNC keyword tag is called asynchronously in the MyClass constructor, Displayvalue (), and the Displayvalue () method executes an await keyword-tagged asynchronous task Getvalueasync (), This asynchronous task must be either a task or a task<tresult> as the return value, and we also see that the actual type returned when the asynchronous task execution completes is void or the Tresult,displayvalue () method await All code after Getvalueasync () will be executed when the asynchronous task is completed.

The code that is actually executed by the Displayvalue () method is as follows:

1  Public voidDisplayvalue ()2 {3system.runtime.compilerservices.taskawaiter<Double> awaiter = Getvalueasync (1234.5,1.01). Getawaiter ();4Awaiter. OnCompleted (() =5         {6             Doubleresult =Awaiter. GetResult ();7System.Diagnostics.Debug.WriteLine ("Value is:"+result);8         });9}

As you can see, the async and await keywords simply make the above code easier to understand.

The output of the program is as follows:

MyClass () End.

Value is:2.47032822920623e-322

Reference content:

Http://www.cnblogs.com/youquan-deng/articles/csharp-regex.html
Http://www.jb51.net/tools/zhengze.html#greedyandlazy
http://blog.csdn.net/tianmuxia/article/details/17675681

C # Learning (v)-Regular expressions, etc.

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.