正規表現クラス

ここでは、.NET Framework の正規表現クラスについて説明します。

Regex

Regex クラスは、変更不可 (読み込み専用) の正規表現を表します。このクラスには静的メソッドも含まれています。静的メソッドを使用すると、他の正規表現クラスのオブジェクトのインスタンスを明示的に作成しなくても、それらのクラスを使用できます。

Regex クラスのインスタンスを作成し、そのオブジェクト初期化時に単純な正規表現を定義するコード例を次に示します。検索用の文字クラス \s に含まれる円記号がリテラル文字であることを示すために、エスケープ文字として円記号が追加されています。

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

Match

Match クラスは、正規表現に一致した結果を表します。入力文字列の中で最初に一致する文字列を見つけるために、Regex クラスの Match メソッドを使用して Match 型のオブジェクトを返す例を次に示します。この例では、Match クラスの Match.Success プロパティを使用して、一致する文字列が検索できたかどうかを示しています。

    ' 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
    // 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

MatchCollection クラスは、成功した重複しない一致文字列のシーケンスを表します。このコレクションは、変更不可 (読み込み専用) であり、パブリック コンストラクタはありません。MatchCollection のインスタンスは、Regex.Matches メソッドによって返されます。

Regex クラスの Matches メソッドを使用して、入力文字列の中で見つかった文字列のすべてを MatchCollection に読み込む例を次に示します。次の例では、一致した各文字列を格納する文字列配列と、各文字列の位置を格納する整数配列に、コレクションをコピーしています。

    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
    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

GroupCollection クラスは、キャプチャされたグループのコレクションを表し、1 回の検索でキャプチャされたグループ セットを返します。このコレクションは、変更不可 (読み込み専用) であり、パブリック コンストラクタはありません。GroupCollection のインスタンスは、Match.Groups プロパティから返されるコレクション内に返されます。

正規表現によってキャプチャされたグループ数を取得して出力するコンソール アプリケーションの例を次に示します。グループ コレクションの各メンバに含まれる、それぞれのキャプチャを抽出する方法の例については、次のセクションの CaptureCollection の例を参照してください。

    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
    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();
        }
    }

この例を実行すると、次の出力が生成されます。

    Number of groups found = 3
    Number of groups found = 3

CaptureCollection

CaptureCollection クラスは、キャプチャされた部分文字列のシーケンスを表し、1 つのキャプチャ グループでキャプチャ済みのキャプチャ セットを返します。キャプチャ グループは量指定子を使用するため、1 回の検索で複数の文字列をキャプチャできます。CaptureCollection クラスのオブジェクトである Captures プロパティは、キャプチャされた部分文字列セットに簡単にアクセスできるように、Match クラスおよび Group クラスのメンバとして提供されます。

たとえば、正規表現 ((a(b))c)+ (量指定子 + は 1 つ以上の文字列が一致することを指定) を使用して文字列 "abcabcabc" から一致する文字列をキャプチャする場合、一致した部分文字列を含む各 GroupCaptureCollection には、3 個のメンバが含まれることになります。

正規表現 (Abc)+ を使用して、文字列 "XYZAbcAbcAbcXYZAbcAb" の中から一致する文字列を 1 つ以上検索するコンソール アプリケーションの例を次に示します。この例は、Captures プロパティを使用して、キャプチャした部分文字列の複数のグループを返す方法を示しています。

    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
    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();
        }
    }

この例を実行すると、次の出力が生成されます。

    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
    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

Group クラスは、1 つのキャプチャ グループによるキャプチャの結果を表します。Group は、量指定子を使用して 1 回の検索で 0 個、1 個、または複数個の文字列をキャプチャできるため、Capture オブジェクトのコレクションが含まれます。GroupCapture から継承しているため、最後にキャプチャされた部分文字列に直接アクセスできます。Group インスタンス自体が、Captures プロパティから返されるコレクションの最終項目と等しいためです。

Group のインスタンスは、Groups プロパティによって返される GroupCollection オブジェクトにインデックスを作成することで返されます。"(?<groupname>)" グループ化構成体が使用されている場合は、インデクサとしてグループ番号またはキャプチャ グループの名前を使用できます。たとえば、C# コードでは、Match.Groups[groupnum] または Match.Groups["groupname"] を使用できます。また、Visual Basic コードでは、Match.Groups(groupnum) または Match.Groups("groupname") を使用できます。

入れ子にしたグループ化構成体を使用して部分文字列をキャプチャし、グループ化するコード例を次に示します。

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

この例を実行すると、次の出力が生成されます。

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

次のコード例では、名前付きグループ化構成体を使用して、"DATANAME:VALUE" 形式のデータを含む文字列から部分文字列をキャプチャします。この正規表現は、コロン (:) でデータを分割します。

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

この正規表現により、次の出力が返されます。

    m.Groups("name").Value = "Section1"
    m.Groups("value").Value = "119900"
    m.Groups["name"].Value = "Section1"
    m.Groups["value"].Value = "119900"

Capture

Capture クラスには、単一の部分表現キャプチャの結果が含まれます。

Group コレクションをループし、Group の各メンバから Capture コレクションを抽出する例を次に示します。さらにこの例では、元の文字列の中で各文字列が見つかった文字位置を変数 posn に、各文字列の長さを変数 length に代入します。

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

参照

関連項目

System.Text.RegularExpressions

その他の技術情報

.NET Framework の正規表現