hakeの日記

Windows環境でプログラミングの勉強をしています。

C# - 正規表現

基本的にはPowerShellExcel VBAのものと同じ感じ。
マッチさせた結果は、MatchやMatchesのインスタンスに格納される。

using System;
using System.Text.RegularExpressions;

//正規表現

class MyMain
{
    public static void Main(string[] args)
    {
        string pattern = @"\w((\w)(\w))";
        string input = "ABCdef";

        //静的メソッド使用
        Console.WriteLine("IsMatch : {0}", Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase));
        //最初にマッチしたものを取得
        Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
        PrintMatch(match);
        Console.WriteLine("---");

        //正規表現オブジェクトのインスタンス使用
        Regex re = new Regex(pattern, RegexOptions.IgnoreCase);
        //マッチするもの全てを取得
        var matches = re.Matches(input);
        Console.WriteLine("Count  : {0}", matches.Count); 
        foreach (Match m in matches)
        {
            PrintMatch(m);
        }
    }

    private static void PrintMatch(Match m)
    {
        Console.WriteLine("Value  : {0}", m.Value);
        Console.WriteLine("Index  : {0}", m.Index);
        Console.WriteLine("Length : {0}", m.Length);
        var gs = m.Groups;
        Console.WriteLine("include {0} Groups", gs.Count);
        for(var i = 0; i < gs.Count; i++)
        {
            if( i == 0 )
            {
                Console.WriteLine("  Groups[{0}](Match)       : {1}", i, gs[i]);
            }
            else
            {
                Console.WriteLine("  Groups[{0}](SubMatch[{1}]) : {2}", i, i-1, gs[i]);
            }

        }
    }
}

 

実行結果

IsMatch : True
Value  : ABC
Index  : 0
Length : 3
include 4 Groups
  Groups[0](Match)       : ABC
  Groups[1](SubMatch[0]) : BC
  Groups[2](SubMatch[1]) : B
  Groups[3](SubMatch[2]) : C
---
Count  : 2
Value  : ABC
Index  : 0
Length : 3
include 4 Groups
  Groups[0](Match)       : ABC
  Groups[1](SubMatch[0]) : BC
  Groups[2](SubMatch[1]) : B
  Groups[3](SubMatch[2]) : C
Value  : def
Index  : 3
Length : 3
include 4 Groups
  Groups[0](Match)       : def
  Groups[1](SubMatch[0]) : ef
  Groups[2](SubMatch[1]) : e
  Groups[3](SubMatch[2]) : f