Regular Expression Studies

Source: Internet
Author: User
So far, many programming languages and tools have supported regular expressions, of course. NET is no exception ,. NET base class library contains a namespace and a series of classes that can fully exert the power of Rule expressions.
The knowledge of regular expressions may be the most worrying thing for many programmers. If you do not have any knowledge about regular expressions, we recommend that you start with the basic knowledge of regular expressions. See Regular expression syntax.

The following describes the regular expressions in C #. The regular expressions in C # are contained in a namespace of the. NET base record. The namespace is System. Text. RegularExpressions. The namespace contains eight classes, one enumeration, and one delegate. They are:
Capture: contains a matching result;
CaptureCollection: the sequence of Capture;
Group: the result of a Group record, inherited by Capture;
GroupCollection: a collection of capture groups.
Match: the matching result of an expression, inherited by the Group;
MatchCollection: a sequence of Match;
MatchEvaluator: The delegate used to perform the replacement operation;
Regex: An Example of the compiled expression.
RegexCompilationInfo: provides information that the compiler uses to compile a regular expression into an independent assembly.
RegexOptions provides the enumerated values used to set regular expressions.
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.

The following describes their usage:
First, let's look at a simple matching example. First, we start to learn from the simple expressions of the Regex and Match classes. Match m = Regex. match ("abracadabra", "(a | B | r) +"); now we 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: MesaageBox. show ("Match =" + m. toString (); in this example, the following output is obtained: Match = abra. This is the matched string.

The Regex class indicates a read-only regular expression class. It also contains various static methods (which will be introduced one by one in the following examples), allowing other regular expression classes to be used without explicitly creating instances of other classes.

The following code example creates an instance of the Regex class and defines a simple regular expression when initializing an object. Declare a Regex object variable: Regex objAlphaPatt;, create an instance of the Regex object, and define its rule: objAlphaPatt = new Regex ("[^ a-zA-Z]");

The IsMatch method indicates whether the regular expression specified by the Regex constructor finds a match in the input string. This is one of the most common methods when we use a C # regular expression. The following example illustrates how to use the IsMatch method:
If (! ObjAlphaPatt. IsMatch ("testisMatchMethod "))
LblMsg. Text = "matched successfully ";
Else
LblMsg. Text = "Mismatch failed ";
The result of executing this code is "matched successfully"
If (! ObjAlphaPatt. IsMatch ("testisMatchMethod7654298 "))
LblMsg. Text = "matched successfully ";
Else
LblMsg. Text = "Mismatch failed ";
The result of executing this code is "the matching fails"

The Escape method uses Escape characters as characters instead of Escape characters. The minimum metacharacters (\, *, + ,? , |, {, [, (,), ^, $,., #, And blank ). The Replace method replaces all the matching items of the character pattern defined by the regular expression with the specified replacement string. The following example shows how to use the Regex object defined above: objAlphaPatt. replace ("this [test] ** replace and escape", Regex. escape ("()"); The returned result is: this \ (\) test \(\)\(\)\(\) \ (\) replace \ (\) and \ (\) escape. If it is not Escape, the returned result is: this () test ()() () replace () and () escape: Unescape reverses the conversions executed by Escape. However, Escape cannot completely reverse Unescape.

The Split method splits the input string into a substring array at the position defined by the regular expression match. For example:
Regex r = new Regex ("-"); // Split on hyphens.
String [] s = r. Split ("first-second-third ");
For (int I = 0; I <s. Length; I ++)
{
Response. Write (s [I] + "<br> ");
}

The execution result is:
First
Second
Third

The Split method looks the same as the Split method of String, but the Split method of string splits the String in a separator determined by a regular expression rather than a group of characters.

The Match method searches for matching items of the regular expression in the input string, and the Match method of the Regex class returns the Match object. The Match class indicates the matching operation result of the regular expression. The following example demonstrates the use of the Match Method and uses the Group attribute of the Match object to return the Group Object:

String text = @ "public string testMatchObj string s string match ";
String pat = @ "(\ w +) \ s + (string )";
// Compile the regular expression.
Regex r = new Regex (pat, RegexOptions. IgnoreCase );
// Match the regular expression pattern against a text string.
Match m = r. Match (text );
Int matchCount = 0;
While (m. Success)
{
Response. Write ("Match" + (++ matchCount) + "<br> ");
For (int I = 1; I <= 2; I ++)
{
Group g = m. Groups [I];
Response. Write ("Group" + I + "= '" + g + "'" + "<br> ");
CaptureCollection cc = g. Captures;
For (int j = 0; j <cc. Count; j ++)
{
Capture c = cc [j];
Response. Write ("Capture" + j + "= '" + c + "', Position =" + c. Index + "<br> ");
}
}
M = m. NextMatch ();
}

The running result of this example is:
Matebook
Group1 = 'public'
Capture0 = 'public', Position = 0
Group2 = 'string'
Capture0 = 'string', Position = 7
Match2
Group1 = 'testmatchobj'
Capture0 = 'testmatchobj ', Position = 14
Group2 = 'string'
Capture0 = 'string', Position = 27
Match3
Group1 = 'S'
Capture0 ='s, Position = 34
Group2 = 'string'
Capture0 = 'string', Position = 36

The MatchCollection class indicates a successful read-only set of non-overlapping matches. The MatchCollection instance is composed of Regex. the following example shows how to find all the Matches specified in Regex in the input string and fill in MatchCollection.

MatchCollection mc;
Regex r = new Regex ("match ");
Mc = r. Matches ("matchcollectionregexmatchs ");
For (int I = 0; I <mc. Count; I ++)
{
Response. Write (mc [I]. Value + "POS:" + mc [I]. Index. ToString () + "<br> ");
}
The instance runs as follows:
Match POS: 0
Match POS: 20

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.