C # application of regular expression in replace !,

Source: Internet
Author: User

C # application of regular expression in replace !,

Over the years, many programming languages and tools have supported regular expressions ,. NET base class library contains a namespace and a series of classes that can fully utilize the power of Rule expressions, and they are also compatible with future rule expressions in Perl 5.

In addition, the regexp class can complete some other functions, such as the combination mode from right to left and expression editing.

In this article, I will briefly introduce System. text. classes and methods in RegularExPRession, examples of string matching and replacement, and detailed information about the group structure. Finally, we will introduce some common expressions that you may use.

Basic knowledge to be mastered

The knowledge of Rule expressions may be one of the things that many programmers often forget. In this article, we will assume that you have mastered the usage of regular expressions, especially the expressions in Perl 5 .. NET regexp class is a superset of expressions in Perl 5, So theoretically it will be a good start point. We also assume that you have basic knowledge of C # syntax and. NET architecture.

If you do not have knowledge about Rule expressions, I suggest you start with the Perl 5 syntax. The authoritative book on Rule expressions is written by Jeffrey fredel. We strongly recommend that you read this book for readers who wish to have a deep understanding of expressions.

RegularExpression combination

The regexp rule class is included in the System. Text. RegularExpressions. dll file. You must reference this file when compiling the application software. For example:

Csc r: System. Text. RegularExpressions. dll foo. cs

The command will create the foo.exe file, which references the System. Text. RegularExpressions file.

Namespace Introduction

The namespace contains only six classes and one definition. They are:

Capture: contains a matching result;
CaptureCollection: the sequence of Capture;
Group: the result of a Group record, inherited by Capture;
Match: the matching result of an expression, inherited by the Group;
MatchCollection: a sequence of Match;
MatchEvaluator: the proxy used to perform the replacement operation;
Regex: An Example of the compiled expression.

The Regex class also contains some static methods:

Escape: Escape the Escape characters in the regex string;
IsMatch: If the expression matches a string, this method returns a Boolean value;
Match: returns the instance of the Match;
Matches: returns a series of Match methods;
Replace: Replace the matching expression with the replacement string;
Split: returns a series of strings determined by expressions;
Unescape: do not escape characters in strings.

Simple Matching

First, we start to learn from simple expressions of the Regex and Match classes.

Match m = Regex. Match ("abracadabra", "(a | B | r) + ");

We now have an instance of the Match class that can be used for testing, for example: if (m. Success )...
If you want to use a matched string, you can convert it into a string:

Console. WriteLine ("Match =" + m. ToString ());

In this example, the following output is obtained: Match = abra. This is the matched string.

String replacement

Simple string replacement is very intuitive. For example, the following statement:

String s = Regex. Replace ("abracadabra", "abra", "zzzz ");

It returns the string zzzzzzcadzzzz, and all matched strings are replaced with zzzzzzz.

Now let's look at a complicated string replacement example:

String s = Regex. Replace ("abra", @ "^ \ s *(.*?) \ S * $ "," $1 ");

This statement returns the string abra, with leading and trailing spaces removed.

The preceding mode is useful for deleting leading and trailing spaces in any string. In C #, we often use letter strings. In a letter string, the compiler does not treat the character "\" as an escape character. When the character "\" is used to specify the Escape Character, @ "..." is very useful. It is also worth mentioning that $1 is used in string replacement, which indicates that the replacement string can only contain the replaced string.

Matching engine details

Now, we use a group structure to understand a slightly complex example. See the following example:

String text = "abracadabra1abracadabra2abracadabra3 ";

String pat = @"

(# Start of the first group

Abra # match the string abra

(# Start of the second group

Cad # matching string cad

)? # End of the second group (optional)

) # End of the first group

+ # Match once or multiple times

";

// Ignore comments using the x modifier

Regex r = new Regex (pat, "x ");

// Obtain the group number list

Int [] gnums = r. GetGroupNumbers ();

// Match for the first time

Match m = r. Match (text );

While (m. Success)

{

// Start with Group 1

For (int I = 1; I <gnums. Length; I ++)

{

Group g = m. Group (gnums [I]);

// Obtain the matched group

Console. WriteLine ("Group" + gnums [I] + "= [" + g. ToString () + "]");

// Calculate the start position and length of the Group

CaptureCollection cc = g. Captures;

For (int j = 0; j <cc. Count; j ++)

{

Capture c = cc [j];

Console. WriteLine ("Capture" + j + "= [" + c. ToString ()

+ "] Index =" + c. Index + "Length =" + c. Length );

}

}

// Next match

M = m. NextMatch ();

}

The output of this example is as follows:
     
Group1 = [abra]

Capture0 = [abracad] Index = 0 Length = 7

Capture1 = [abra] Index = 7 Length = 4

Group2 = [cad]

Capture0 = [cad] Index = 4 Length = 3

Group1 = [abra]

Capture0 = [abracad] Index = 12 Length = 7

Capture1 = [abra] Index = 19 Length = 4

Group2 = [cad]

Capture0 = [cad] Index = 16 Length = 3

Group1 = [abra]

Capture0 = [abracad] Index = 24 Length = 7

Capture1 = [abra] Index = 31 Length = 4

Group2 = [cad]

Capture0 = [cad] Index = 28 Length = 3

First, we start by examining the string pat, which contains an expression. The first capture starts with the first parentheses, and then the expression matches with an abra. The second capture group starts from the second parentheses, but the first capture group is not over yet. This means that the first group matches abracad, the matching result of the second group is only cad. Therefore, if you use? To make cad an optional match, the matching result may be abra or abracad. Then, the first group ends and the expression is required to be matched multiple times by specifying the + symbol.

Now let's take a look at what happens in the matching process. First, call the constructor method of Regex to create an instance of the expression and specify various options. In this example, because there is a comment in the expression, the x option is selected, and some spaces are used. When the x option is enabled, the expression ignores comments and spaces without escape.

Then, retrieve the list of group numbers defined in the expression. Of course you can use these numbers explicitly. Here you use the programming method. If a named group is used, this method is also very effective as a way to create a fast index.

The next step is to complete the first matching. Use a loop to test whether the current matching is successful. Next, repeat this operation on the group list from group 1. In this example, group 0 is not used because group 0 is a fully matched string. To collect all matched strings as a single string, group 0 is used.

We track the CaptureCollection in each group. Normally, each group can have only one capture, but Group1 in this example has two capture: Capture0 and Capture1. If you only need the ToString of Group1, you will get only abra. Of course, it will also match abracad. The value of ToString in the group is the value of the last Capture in its CaptureCollection, which is exactly what we need. If you want the entire process to end after matching abra, you should delete the + symbol from the expression to let the regex engine know that we only need to match the expression.

Comparison between process-based and expression-based methods

Generally, users who use rule expressions can be divided into the following two categories: the first type of users should try not to use rule expressions, but use procedures to perform operations that need to be repeated; the second type of users make full use of the functions and power of the Rule Expression Processing Engine, and use the process as little as possible.

For most of our users, the best solution is to use both of them. I hope this article will illustrate the role of the regexp class in the. NET language and its advantages and disadvantages between performance and complexity.

Process-based model

We often need to use a function in programming to match a part of a string or process other strings. Below is an example of matching words in a string:

String text = "the quick red fox jumped over the lazy brown dog .";

System. Console. WriteLine ("text = [" + text + "]");

String result = "";

String pattern = @ "\ w + | \ W + ";

Foreach (Match m in Regex. Matches (text, pattern ))

{

// Obtain the matched string

String x = m. ToString ();

// If the first character is lowercase

If (char. IsLower (x [0])

// Convert to uppercase

X = char. ToUpper (x [0]) + x. Substring (1, x. Length-1 );

// Collect all characters

Result + = x;

}

System. Console. WriteLine ("result = [" + result + "]");

As shown in the preceding example, we use the foreach statement in C # to process each matching character and complete corresponding processing. In this example, a new result string is created. The output of this example is as follows:

Text = [the quick red fox jumped over the lazy brown dog.]

Result = [The Quick Red Fox Jumped Over The Lazy Brown Dog.]

Expression-based mode

Another way to complete the functions in the above example is through a MatchEvaluator. The new Code is as follows:

Static string CapText (Match m)

{

// Obtain the matched string

String x = m. ToString ();

// If the first character is lowercase

If (char. IsLower (x [0])

// Convert to uppercase

Return char. ToUpper (x [0]) + x. Substring (1, x. Length-1 );

Return x;

}



Static void Main ()

{

String text = "the quick red fox jumped over

Lazy brown dog .";

System. Console. WriteLine ("text = [" + text + "]");

String pattern = @ "\ w + ";

String result = Regex. Replace (text, pattern,

New MatchEvaluator (Test. CapText ));

System. Console. WriteLine ("result = [" + result + "]");

}

At the same time, it is important to note that this mode is very simple because you only need to modify words without modifying non-words.

Common expressions

To better understand how to use rule expressions in the C # environment, I have written some rule expressions that may be useful to you. These expressions have been used in other environments, hope to help you.

Roman numerals

String p1 = "^ m * (d? C {0, 3} | c [dm]) "+" (l? X {0, 3} | x [lc]) (v? I {0, 3} | I [vx]) $ ";

String t1 = "vii ";

Match m1 = Regex. Match (t1, p1 );

Exchange the first two words

String t2 = "the quick brown fox ";

String p2 = @ "(\ S +) (\ s +) (\ S + )";

Regex x2 = new Regex (p2 );

String r2 = x2.Replace (t2, "$3 $2 $1", 1 );

Guan jianzi = Value

String t3 = "myval = 3 ";

String p3 = @ "(\ w +) \ s * = \ s * (. *) \ s * $ ";

Match m3 = Regex. Match (t3, p3 );

Implement 80 characters per line

String t4 = "********************"

+ "******************************"

+ "******************************";

String p4 = ". {80 ,}";

Match m4 = Regex. Match (t4, p4 );

Month/day/year hour: minute: Second Time Format

String t5 = "01/01/01 16:10:01 ";

String p5 = @ "(\ d +)/(\ d +) :( \ d + )";

Match m5 = Regex. Match (t5, p5 );

Change directory (applicable only to Windows)

String t6 = @ "C: \ Documents ents and Settings \ user1 \ Desktop \";

String r6 = Regex. Replace (t6, @ "\ user1 \", @ "\ user2 \\");

Extended 16-bit escape characters

String t7 = "% 41"; // capital

String p7 = "% ([0-9A-Fa-f] [0-9A-Fa-f])";

String r7 = Regex. Replace (t7, p7, HexConvert );

Delete comments in C Language (to be improved)

String t8 = @"

/*

* Notes for traditional styles

*/

";

String p8 = @"

/\ * # Match the delimiters starting with the Annotation

.*? # Matching comments

\ */# End Separator of matching Annotation

";

String r8 = Regex. Replace (t8, p8, "", "xs ");

Deletes spaces at the start and end of a string.

String t9a = "leading ";

String p9a = @ "^ \ s + ";

String r9a = Regex. Replace (t9a, p9a ,"");

String t9b = "trailing ";

String p9b = @ "\ s + $ ";

String r9b = Regex. Replace (t9b, p9b ,"");

Add character n after character \ to make it a real New Line

String t10 = @ "\ ntest \ n ";

String r10 = Regex. Replace (t10, @ "\ n", "\ n ");

Convert IP addresses

String t11 = "55.54.53.52 ";

String p11 = "^" +

@ "([01]? \ D | 2 [0-4] \ d | 25 [0-5]) \. "+

@ "([01]? \ D | 2 [0-4] \ d | 25 [0-5]) \. "+

@ "([01]? \ D | 2 [0-4] \ d | 25 [0-5]) \. "+

@ "([01]? \ D | 2 [0-4] \ d | 25 [0-5]) "+

"$ ";

Match m11 = Regex. Match (t11, p11 );

Delete the path contained in the file name

String t12 = @ "c: \ file.txt ";

String p12 = @ "^ .*\\";

String r12 = Regex. Replace (t12, p12 ,"");

Concatenate rows from multiple strings

String t13 = @ "this is

A split line ";

String p13 = @ "\ s * \ r? \ N \ s *";

String r13 = Regex. Replace (t13, p13 ,"");

Extract all numbers in the string

String t14 = @"

Test 1

Test 1, 2.3

Test 47

";

String p14 = @ "(\ d + \.? \ D * | \. \ d + )";

MatchCollection mc14 = Regex. Matches (t14, p14 );

Find all uppercase letters

String t15 = "This IS a Test of all Caps ";

String p15 = @ "(\ B [^ \ Wa-z0-9 _] + \ B )";

MatchCollection mc15 = Regex. Matches (t15, p15 );

Find lowercase words

String t16 = "This is A Test of lowercase ";

String p16 = @ "(\ B [^ \ WA-Z0-9 _] + \ B )";

MatchCollection mc16 = Regex. Matches (t16, p16 );

Find the words whose first letter is uppercase.

String t17 = "This is A Test of Initial Caps ";

String p17 = @ "(\ B [^ \ Wa-z0-9 _] [^ \ WA-Z0-9 _] * \ B )";

MatchCollection mc17 = Regex. Matches (t17, p17 );

Find links in a simple HTML language


String t18 = @"

<Html>

<A href = "" first.htm ""> first tag text </a>

<A href = "" next.htm ""> next tag text </a>

</Html>

";

String p18 = @ "<A [^>] *? HREF \ s * = \ s * ["" ']? "+ @" ([^ '">] + ?) ['""]?> ";

MatchCollection mc18 = Regex. Matches (t18, p18, "si ");

Reprinted from: http://www.aspnetjia.com

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.