. Net regular expression class

Source: Internet
Author: User
Net Framework developer Guide  
The following sections describe the. NET Framework regular expression class. Regex

The Regex class indicates an unchangeable (read-only) Regular Expression class. It also contains various static methods that allow other regular expression classes to be used without explicitly creating instances of other classes.

The following code example createsRegExClass instance and define a simple regular expression when initializing the object. Note that the additional backslash is used as the escape character\s The backslash in the matching character class is specified as the original literal character.

[Visual Basic]    ' Declare object variable of type Regex.    Dim r As Regex     ' Create a Regex object and define its regular expression.    r = New Regex("\s2000")[C#]    // Declare object variable of type Regex.    Regex r;     // Create a Regex object and define its regular expression.    r = new Regex("\\s2000"); 
Match

The Match class indicates the result of the regular expression matching operation. The following example usesRegExClassMatchMethod returnMatchType object to find the first match in the input string. This example usesMatchThe Match. Success attribute of the class to indicate whether a Match has been found.

[Visual Basic]    ' cCreate a new Regex object.    Dim r As New Regex("abc")     ' Find a single match in the input string.    Dim m As Match = r.Match("123abc456")     If m.Success Then        ' Print out the character position where a match was found.         ' (Character position 3 in this case.)        Console.WriteLine("Found match at position " & m.Index.ToString())    End If[C#]    // Create a new Regex object.    Regex r = new Regex("abc");     // Find a single match in the string.    Match m = r.Match("123abc456");     if (m.Success)     {        // Print out the character position where a match was found.         // (Character position 3 in this case.)        Console.WriteLine("Found match at position " + m.Index);    }
MatchCollection

The MatchCollection class indicates a successful non-overlapping matching sequence. The set is unchangeable (read-only) and there is no public constructor.MatchcollectionThe instance is composedRegEx. MatchesAttribute returned.

The following example usesRegExThe Matches method of the class. It is filled by all the Matches found in the input string.Matchcollection. In this example, the set is copied to a string array and an integer array. The string array is used to save each matching item, and the integer array is used to indicate the position of each matching item.

[Visual Basic]    Dim mc As MatchCollection    Dim results(20) As String    Dim matchposition(20) As Integer    ' Create a new Regex object and define the regular expression.    Dim r As New Regex("abc")    ' Use the Matches method to find all matches in the input string.    mc = r.Matches("123abc4abcd")    ' Loop through the match collection to retrieve all     ' matches and positions.    Dim i As Integer    For i = 0 To mc.Count - 1        ' Add the match string to the string array.        results(i) = mc(i).Value        ' Record the character position where the match was found.        matchposition(i) = mc(i).Index    Next i[C#]    MatchCollection mc;    String[] results = new String[20];    int[] matchposition = new int[20];        // Create a new Regex object and define the regular expression.    Regex r = new Regex("abc");     // Use the Matches method to find all matches in the input string.    mc = r.Matches("123abc4abcd");    // Loop through the match collection to retrieve all     // matches and positions.    for (int i = 0; i < mc.Count; i++)     {        // Add the match string to the string array.           results[i] = mc[i].Value;        // Record the character position where the match was found.        matchposition[i] = mc[i].Index;       }
GroupCollection

The GroupCollection class indicates the set of captured groups and returns the set of captured groups in a single match. The set is unchangeable (read-only) and there is no public constructor.GroupcollectionInMatch. GroupsThe Set returned by the property.

The following console application example finds and outputs the number of groups captured by regular expressions. For an example of how to extract capture items from each member of a group set, see the following sectionCapture collectionExample.

[Visual Basic]    Imports System    Imports System.Text.RegularExpressions    Public Class RegexTest        Public Shared Sub RunTest()            ' Define groups "abc", "ab", and "b".            Dim r As New Regex("(a(b))c")             Dim m As Match = r.Match("abdabc")            Console.WriteLine("Number of groups found = " _            & m.Groups.Count.ToString())        End Sub                Public Shared Sub Main()            RunTest()        End Sub    End Class[C#]    using System;    using System.Text.RegularExpressions;    public class RegexTest     {        public static void RunTest()         {            // Define groups "abc", "ab", and "b".            Regex r = new Regex("(a(b))c");             Match m = r.Match("abdabc");            Console.WriteLine("Number of groups found = " + m.Groups.Count);        }        public static void Main()         {            RunTest();        }    }

This example generates the following output.

[Visual Basic]    Number of groups found = 3[C#]    Number of groups found = 3
CaptureCollection

The capturecollection class indicates the sequence of captured substrings and returns a collection of captured results executed by a single capture group. Because of the qualifier, the capture group can capture multiple strings in a single match.CapturesProperty (CapturecollectionClass Object) is provided as a member of the match and group classes to facilitate access to the collection of captured substrings.

For example, if you use a regular expression((a(b))c)+(The + qualifier specifies one or more matches) capture the match from the string "abcabcabc", then each matchedGroupOfCapturecollectionIt will contain three members.

The following console application example uses a regular expression(Abc)+To find one or more matches in the string "xyzabcabcabcxyzabcab. This example illustrates how to useCapturesAttribute to return multiple groups of captured substrings.

[Visual Basic]    Imports System    Imports System.Text.RegularExpressions    Public Class RegexTest        Public Shared Sub RunTest()            Dim counter As Integer            Dim m As Match            Dim cc As CaptureCollection            Dim gc As GroupCollection            ' Look for groupings of "Abc".            Dim r As New Regex("(Abc)+")             ' Define the string to search.            m = r.Match("XYZAbcAbcAbcXYZAbcAb")            gc = m.Groups                        ' Print the number of groups.            Console.WriteLine("Captured groups = " & gc.Count.ToString())                        ' Loop through each group.            Dim i, ii As Integer            For i = 0 To gc.Count - 1                cc = gc(i).Captures                counter = cc.Count                                ' Print number of captures in this group.                Console.WriteLine("Captures count = " & counter.ToString())                                ' Loop through each capture in group.                            For ii = 0 To counter - 1                    ' Print capture and position.                    Console.WriteLine(cc(ii).ToString() _                        & "   Starts at character " & cc(ii).Index.ToString())                Next ii            Next i        End Sub            Public Shared Sub Main()            RunTest()         End Sub    End Class[C#]    using System;    using System.Text.RegularExpressions;    public class RegexTest         {        public static void RunTest()         {            int counter;            Match m;            CaptureCollection cc;            GroupCollection gc;            // Look for groupings of "Abc".            Regex r = new Regex("(Abc)+");             // Define the string to search.            m = r.Match("XYZAbcAbcAbcXYZAbcAb");             gc = m.Groups;            // Print the number of groups.            Console.WriteLine("Captured groups = " + gc.Count.ToString());            // Loop through each group.            for (int i=0; i < gc.Count; i++)             {                cc = gc[i].Captures;                counter = cc.Count;                                // Print number of captures in this group.                Console.WriteLine("Captures count = " + counter.ToString());                                // Loop through each capture in group.                for (int ii = 0; ii < counter; ii++)                 {                    // Print capture and position.                    Console.WriteLine(cc[ii] + "   Starts at character " +                         cc[ii].Index);                }            }        }        public static void Main() {            RunTest();        }    }

This example returns the following output.

[Visual Basic]    Captured groups = 2    Captures count = 1    AbcAbcAbc   Starts at character 3    Captures count = 3    Abc   Starts at character 3    Abc   Starts at character 6    Abc   Starts at character 9[C#]    Captured groups = 2    Captures count = 1    AbcAbcAbc   Starts at character 3    Captures count = 3    Abc   Starts at character 3    Abc   Starts at character 6    Abc   Starts at character 9
Group

The Group class indicates the results from a single capture group. BecauseGroupZero, one, or more strings can be captured in a single match (using a qualifier), so it containsCaptureObject set. BecauseGroupInherited fromCaptureSo you can directly access the final captured substring (GroupThe instance itself is equivalentCapturesThe last entry of the Set returned by the property ).

GroupThe instance is composedMatch. Groups(Groupnum) returned by the property, or when "(? <Groupname>) "When the group is constructedMatch. Groups("Groupname") returned by the property.

The following code uses a nested grouping structure to capture substrings to a group.

[Visual Basic]    Dim matchposition(20) As Integer    Dim results(20) As String    ' Define substrings abc, ab, b.    Dim r As New Regex("(a(b))c")     Dim m As Match = r.Match("abdabc")    Dim i As Integer = 0    While Not (m.Groups(i).Value = "")           ' Copy groups to string array.       results(i) = m.Groups(i).Value            ' Record character position.        matchposition(i) = m.Groups(i).Index         i = i + 1    End While[C#]    int[] matchposition = new int[20];    String[] results = new String[20];    // Define substrings abc, ab, b.    Regex r = new Regex("(a(b))c");     Match m = r.Match("abdabc");    for (int i = 0; m.Groups[i].Value != ""; i++)     {        // Copy groups to string array.        results[i]=m.Groups[i].Value;         // Record character position.        matchposition[i] = m.Groups[i].Index;     }

This example returns the following output.

[Visual Basic]    results(0) = "abc"   matchposition(0) = 3    results(1) = "ab"    matchposition(1) = 3    results(2) = "b"     matchposition(2) = 4[C#]    results[0] = "abc"   matchposition[0] = 3    results[1] = "ab"    matchposition[1] = 3    results[2] = "b"     matchposition[2] = 4

The following code example uses a named grouping structure to capture a substring from a string that contains data in the "dataname: Value" format. The regular expression splits data using the colon.

[Visual Basic]    Dim r As New Regex("^(?<name>\w+):(?<value>\w+)")    Dim m As Match = r.Match("Section1:119900")[C#]    Regex r = new Regex("^(?<name>\\w+):(?<value>\\w+)");    Match m = r.Match("Section1:119900");

This regular expression returns the following output results.

[Visual Basic]    m.Groups("name").Value = "Section1"    m.Groups("value").Value = "119900"[C#]    m.Groups["name"].Value = "Section1"    m.Groups["value"].Value = "119900"
Capture

The capture class contains the results captured by a single subexpression.

The following example showsGroupFromGroupExtracted from each memberCaptureSet, and set the variablePosnAndLengthThe positions of Characters in the initial string and the length of each string are allocated respectively.

[Visual Basic] Dim r As Regex Dim m As Match Dim cc As CaptureCollection Dim posn, length As Integer r = New Regex ("(abc) *") m = r. match ("bcabcabc") Dim I, j As Integer I = 0 While m. groups (I ). value <> "" 'Grab the Collection for Group (I ). cc = m. groups (I ). captures For j = 0 To cc. count-1 'position of Capture object. posn = cc (j ). index 'length of Capture object. length = cc (j ). length Next j I + = 1 End While [C #] Regex r; Match m; CaptureCollection cc; int posn, length; r = new Regex ("(abc) *"); m = r. match ("bcabcabc"); for (int I = 0; m. groups [I]. value! = ""; I ++) {// Capture the Collection for Group (I ). cc = m. groups [I]. captures; for (int j = 0; j <cc. count; j ++) {// Position of Capture object. posn = cc [j]. index; // Length of Capture object. length = cc [j]. length ;}}
See

. NET Framework Regular Expression | system. Text. regularexpressions




Related
Interpreting Regular Expressions in C #
Http://www.knowsky.com/4202.html

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.