Regular Expression Classes

Source: Internet
Author: User

The. NET Framework Regular expression classes are described in the following sections. Regex

The Regex class represents a mutable (read-only) regular expression class. It also contains a variety of static methods that allow you to use other regular expression classes 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 the object is initialized. Note that the additional backslash is used as the escape character, which specifies the backslash in the/s matching character class as the 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.
    
Match

The match class represents the result of a regular expression-matching operation. The following example uses the match method of the Regex class to return an object of type match so that the first occurrence in the input string is found. This example uses the Match.Success property of the match 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 ' input string.
    Dim m as Match = R.match ("123abc456") 
    If m.success Then
        ' Print out the character position where a match is found . 
        ' (Character position 3 in the case.)
        Console.WriteLine ("Found match at position" & m.index.tostring ()) End
    If
[C #]
    //Create a new Regex obje Ct.
    Regex r = new Regex ("abc"); 
    Find a single match in the string.
    Match m = R.match ("123abc456"); 
    if (m.success) 
    {
        //Print out of the character position where a match was found. 
        (Character position 3 in the case.)
        Console.WriteLine ("Found match at position" + M.index);
    }
MatchCollection

The MatchCollection class represents a successful sequence of non-overlapping matches. The collection is immutable (read-only) and does not have a public constructor. The instance of MatchCollection is returned by the regex.matches property.

The

The following example uses the matches method of the Regex class to populate MatchCollection with all matches found in the input string. The example copies the collection to a string array and an integer array where the string array holds each match, and an array of integers indicates the position of each match.

[Visual basic] Dim mc As MatchCollection Dim results As String Dim matchposition () as Integer ' Create a new Regex obj
    ECT and define the regular expression.
    Dim R as New Regex ("abc") ' use of 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 is 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;
        The record of the character position where the match was found. Matchposition[i] = Mc[i].   
    Index; }
groupcollection

The GroupCollection class represents a collection of captured groups and returns a collection of groups captured in a single match. The collection is immutable (read-only) and does not have a public constructor. The groupcollection instance is returned in the collection returned by the match.groups property.

The following console application example finds and outputs the number of groups captured by a regular expression. For an example of how to extract individual capture items from each member of a group collection, see the Capture Collection example in the following section.

[visual basic] Imports System imports System.Text.RegularExpressions public class Rege
            Xtest 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 Gro
            UPS 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",
            D "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 (); }
    }

The example produces the following output.

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

The CaptureCollection class represents a sequence of captured substrings and returns a collection of captures that are executed by a single capturing group. Because of qualifiers, capturing groups can capture multiple strings in a single match. The captures property (the object of theCaptureCollection Class) is provided as a member of the Match and group class to facilitate access to the collection of captured substrings.

For example, if you use a regular expression ((a (b)) c) + (where the + qualifier specifies one or more matches) to capture a match from the string "Abcabcabc", the capturecollection of each matching Group of substrings will contain three members.

The following console application example uses the regular expression (ABC) + to find one or more matches in the string "XYZAbcAbcAbcXYZAbcAb". The example illustrates the use of the captures property to return multiple sets 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 A
            S 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   Star TS at character 3
    ABC   starts at character 6
    ABC   starts at character 9
[C #]
    captured groups = 2< C13/>captures count = 1
    abcabcabc   starts at character 3
    captures count = 3
    Abc   starts at charact ER 3
    ABC   starts at character 6
    ABC   starts at character 9
Group

The group class represents the results from a single capturing group. Because Group can capture 0, one, or more strings (using qualifiers) in a single match, it contains a collection of Capture objects. Because group inherits from Capture, you can directly access the last captured substring (thegroup instance itself is equivalent to captures property to the last item of the collection returned by the

The instance of group is returned by the match.groups(groupnum) attribute or, in the case of a "(?<groupname>)" grouping construct, by a The Match.Groups("GroupName") property returns.

The following code example uses nested grouping constructs to capture substrings into groups.

[Visual Basic]
    Dim Matchposition
    As Integer Dim results 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). V Alue = "")    
       ' 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 construct to capture a substring from a string containing data in "Dataname:value" format, and the regular expression splits the data by a 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 output shown below.

[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 from a single child expression capture.

The following example loops through the group collection, extracts the Capture collection from each member of the group , and assigns the variable posn and length to the character position found in the initial string of each string. And the length of each string.

[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 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; }
    }

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.