C # Regular expression programming (ii): Regex class Usage

Source: Internet
Author: User

The previous article describes the relationships between classes in C # about regular expressions, and their methods, which are mainly about the use of the Regex class, and the match and MatchCollection classes are discussed in the next article.
For the application of regular expression, it can be divided into verification, extraction, segmentation and substitution. Validation and simple substitution can be achieved simply by using the Regex class.
Implementing validation with the Regex class
After 2009 years of filing and DNS stop parsing turmoil, most of the feedback sites and forums have filtered some sensitive words, articles containing such sensitive words are either replaced or forbidden to publish, using the Regex class to achieve this function, here is an example:

/// <summary>///Check if there is a sensitive word "Sun Quan" in the string./// </summary> Public voidIsmatchdemo () {stringSource ="Liu bei abc Guan yu ABC fei ABC Zhao Yun ABC Zhuge Liang ABC Sun quan ABC Zhou yu ABC lu su abc Cao Xu you guo Jia need Akira Yuan Shao"; Regex regex=NewRegex ("Sun Quan"); //if (Regex.IsMatch (Source, "Sun Quan"))//The following sentence is the same as the one that is commented out above    if(regex.) IsMatch (source)) {Console.WriteLine ("The string contains a sensitive word: Sun Quan! "); }

Output: The string contains a sensitive word: Sun Quan!
For the above example, if the string to be checked contains "Sun Quan", the keyword will output a hint on the console, of course, in the actual application may contain the forbidden Word content is not allowed to commit rather than just hint. However, there is still a way to bypass this situation, you can use "sun-right" or "Sun + power" to bypass the verification.
For the Chinese string is also more to say, for the English string also to consider the case of each letter. For example, we prohibit a keyword in the content (such as CCTV, or CCAV), do we want to do the case of each letter in the string of case of a combination of multiple verification? No, it's not necessary at all, here's an example:

/// <summary>///Check if there is any case of "Def" in the string/// </summary> Public voidismatchdemowithoption () {stringSource ="Liu bei abc Guan yu ABC fei ABC Zhao Yun ABC Zhuge Liang ABC Sun quan ABC Zhou yu ABC lu su ABC caocao def xu you Guo Jia need to shake Yuan Shao"; Regex regex=NewRegex ("def", regexoptions.ignorecase); if(regex.) IsMatch (source)) {Console.WriteLine ("The string contains a sensitive word: def! "); }}

Output: The string contains a sensitive word: def!

In the example above, the regex was instantiated with two constructors with parameters, with the second parameter being the RegexOptions enumeration mentioned in the previous article, regexoptions.ignorecase representing the match string regardless of whether the case is consistent or not.
In addition, there are some static and instance methods with the same functions in the Regex, such as the IsMatch () method, in the first example I have also written an example of two methods, as follows:

New Regex (" Sun Quan "); // if (Regex.IsMatch (Source, "Sun Quan")) // The following sentence is the same as the one that is commented out above if (regex.) IsMatch (source))

In fact, there are many classes in the. NET framework that have similar situations in which static and non-static classes such as file and FileInfo are available under the System.IO namespace, in fact they provide similar functionality, in the words "What is this for" in small Shenyang? Part of it comes from efficiency considerations, and there are factors that make it easy to write code and look concise. For the occasional half-time scenario, it is recommended to use a static method, which is likely to be more efficient (since regular expressions with static method calls are internally cached and 15 are cached by default, you can change the number of caches by setting the CacheSize property of the Regex class). If you want to use it multiple times in a loop, take an example approach.
Replace with the Regex class
The above processing is only to see if there are prohibited keywords in the content of the submission, in fact, can sometimes do to replace the Forbidden keyword, such as the above used in the string of any form of "ABC" replaced with "|", here is an example:

/// <summary>///implementing the string substitution feature/// </summary> Public voidReplace () {stringSource ="Liu bei abc Guan yu ABC fei ABC Zhao Yun ABC Zhuge Liang ABC Sun quan ABC Zhou yu ABC lu su ABC caocao def xu you Guo Jia need to shake Yuan Shao"; Regex regex=NewRegex ("ABC", regexoptions.ignorecase); stringResult=regex. Replace (Source,"|"); Console.WriteLine ("Original string:"+source); Console.WriteLine ("the replaced string:"+result);}


Output Result:
Original string: Liu Bei abc Guan yu ABC fei ABC Zhao Yun ABC Zhuge Liang ABC Sun quan ABC Zhou yu ABC lu su ABC caocao def xu you Guo Jia need to shake Yuan Shao
Replaced string: Liu Bei | Guan Yu | Zhang Fei | zhao Yun | Zhuge Liang | Sun Quan | Zhou Yu | lu su | Caocao def xu you Guo Jia need to shake Yuan Shao
In fact, sometimes we may encounter more than that, for example, sometimes we want to add any form of "ABC" and "DEF" in the string to HTML form, that is, replace it with <b>abc</b> and <b>def. </b> This form, of course, remains consistent with the original case form, the code is as follows:

/// <summary>///implementing the string substitution feature/// </summary> Public voidReplacematchevaluator () {stringSource ="Liu bei abc Guan yu ABC fei ABC Zhao Yun ABC Zhuge Liang ABC Sun quan ABC Zhou yu ABC lu su ABC caocao def xu you Guo Jia need to shake Yuan Shao"; Regex regex=NewRegex ("[A-z]{3}", regexoptions.ignorecase); stringresult = Regex. Replace (Source,NewMatchEvaluator (Outputmatch)); Console.WriteLine ("Original string:"+source); Console.WriteLine ("the replaced string:"+result);}/// <summary>///MatchEvaluator The method that is called in the delegate to process the matching result/// </summary>/// <param name= "Match" >single regular expression matching during Operation</param>/// <returns></returns>Private stringOutputmatch (match match) {return "<b>"+ Match. Value +"</b>";}


The output results are as follows:
Original string: Liu Bei abc Guan yu ABC fei ABC Zhao Yun ABC Zhuge Liang ABC Sun quan ABC Zhou yu ABC lu su ABC caocao def xu you Guo Jia need to shake Yuan Shao
Replaced string: Liu Bei <b>ABC</b> Guan Yu <b>ABc</b> Zhang Fei <b>Abc</b> Zhao Yun <b>abc</b> Zhuge Liang <b>aBC</b> Sun Quan <b>abC</b> Zhou Yu <b>AbC</b> lu su <b>aBc</b> Cao <b>def </b> Xu You Guo Jia need to shake Yuan Shao
In the example above, we used the MatchEvaluator delegate and also involved the match class (the match class will be described in the next article), and the match class used in the MatchEvaluator delegate represents a single regular expression match. The purpose of completing the substitution is achieved by changing the value of values in the match instance.
In this article, we only describe some simple usages of the Regex class and do not tell the relevant knowledge of regular expressions, but even so it can alleviate some of our work, learning and using regular expressions flexibly is a long-term accumulation process.

C # Regular expression programming (ii): Regex class Usage

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.