C # Use of the regular expression Regex class

Source: Internet
Author: User
Tags net regex expression engine

As a tool for text processing-the Perl language plays an important role in the most powerful support for regular expressions, many other languages use perl-style regular expressions to develop corresponding engines when they are added to the Regular Expression Engine. I have been using the perl language to process text for some time, and I have been developing php for several years. For example, php has a perl-Compatible Regular Expression Engine, the corresponding regular expression functions are prefixed with p, such as preg_replace, preg_match, and preg_split .. The. NET Class Library also supports regular expressions. The Regex class located in the System. Text. RegularExpressions namespace encapsulates the attributes and usage of all regular expressions. This Regex class under the. NET class library is described in detail in the C # language. It can be found that the support for regular expressions in all languages is always the same, and it is very good to learn by analogy.

All the friends who have used regular expressions know that regular expressions are used to specify a rule to process complex texts. (For simple processing, you can use the built-in string processing functions in general languages, and it is more efficient ). In this way, the effect is nothing more than replacing the specific items in the string with another specific item in one mode, matching the content of interest in the text in one mode, and using a special mode split text.

Constructor: used to construct a regular expression object. The source code declaration is as follows:
The public constructor can be directly used. The former uses a regular expression string to construct the object, and the latter uses the regular expression string and expression option to construct the object. The RegexOptions option of the regular expression is an enumeration type used to set the pattern correction of the regular expression. This option of C # has the following items: Multiline -- treats the string as multiple rows, ". "will not match the line break (mask is 2) Singleline -- treat the string as a single line,". "to match the linefeed (mask: 16) IgnorePatternWhitespace -- ignore non-escape spaces in the pattern expression, and enable the annotation represented by # (mask: 32) none -- do not set the option (mask is 0) IgnZ mask? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vcmVDYXNlIKGqoaoguvbC1NfWt/release/e4xM6qtNPT0tbB1/release + jrL/J0tS807/release +/R1NbQtcTH + release Release/zD + 7vyseC6xbXE1 + mjrMq5tcPOtMP8w/u1xNSywKi6xb/J0tSz5LWxt8eytrvx1 + release/release + release/K9tGhz + release + 7 RodTxtc TKsbry1rG908q508OwtM670 + uhsA = "" can be connected. Match: When the pattern is used for matching ,. NET provides three functions: IsMatch, Match, and Matches. The first returns a Boolean value to indicate whether the matching is successful, and the second returns the matching result Match object, contains the matching result content, and the third is to return a set of matching objects, including all matching objects. All declarations of the above functions are as follows:
IsMatch provides a match for the input string and a specified starting position. It also provides a static function to save the trouble of constructing an object and directly pass in the pattern for matching. The following code shows the result.
            string text = @"12345qwert";            if (Regex.IsMatch(text, @"[\d]+"))            {                Console.WriteLine("success");            }            else            {                Console.WriteLine("fail");            }

The Match function also provides the input string matching, which starts to Match the specified starting position, or the matching length specified by a colleague. The corresponding static version is similar. After a successful Match, a Match object is returned, which contains the following information: the matched information Capture and the matched Group information Group, capture contains the matched string Value, Length, and Index at the starting position in the source string. Group has the Group name and whether Success is successful, at the same time, the Match object contains the NextMatch attribute, which is used to only Match the next matching object (if there are multiple matching successful items), and the Result method replaces the currently matched string with a string. The Match function returns only the first matched group, that is, the group 0. The entire regular expression matches the entire group. The Matches function also provides the input string and the specified starting position to return all matching object sets.
            string text = @"12345qwert67890";            Regex rg = new Regex( @"(?
 
  [\d])\d+");            if (rg.IsMatch(text,0))            {                MatchCollection mts = rg.Matches(text,0);                foreach(Match mt in mts )                {                    Console.WriteLine("success:" + mt.Value);                }            }            else            {                Console.WriteLine("fail");            }
 


Replace: in fact, the Result method is also provided in the Match function to Replace the matching item, but the function is insufficient. The following is the replacement method in the Regex class:
The Replace method can be used to Replace the input text directly with the specified text, or to specify the replacement times and start position. You can also use the MatchEvaluator object to Replace it. This object uses the Match object matching the Replace word as a delegate of the parameter and replaces each matching item. For simple replacement, you can directly use the string parameter to replace the matching item and specify the number of replicas or the starting position. For complex matching, use the MatchEvaluator delegate. For details, refer to http://www.dotnetperls.com/regex-replace. Split: after finding the matching item, the source string of this phase is returned. Definition:
The definition of this method is relatively simple, that is, finding the matching item and then splitting the string to obtain the splitting result. You can also specify the number of array elements to be split. The test is as follows:
            string text = @"12345qwert67890";            Regex rg = new Regex( @"(?
 
  [\d])\d+");            string [] strArr = rg.Split(text,10);            foreach(string str in strArr )            {                Console.WriteLine("success:{0}", str);            }
 

From the above figure, we can see that when there is a group, the matching results are split according to the position order in the source string. In addition to the preceding content ,. NET Regex class also provides the following methods: unescape/Escape -- convert any Escape character in the input string/convert common characters to Escape character CompileToAssembly -- compile one or more specified Regex objects as named assembly
GroupNameFromNumber/GroupNumberFromName -- Obtain the group number or perform the opposite operation on the named group
GetGroupNames/GetGroupNumbers -- returns the group number or group name of Multiple matching items.

Related Article

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.