C# 入門 & 実践 / C sharp

4-19. 正規表現 / RegularExpressions - 1 - 検索 / MatchCollection


普通の検索です。
RegularExpressions ネームスペースを使用します。

using System.Text.RegularExpressions;

        static void Main()
        {
            string str = @"Microsoft .Net Frameword 2.0 
Microsoft .Net Frameword 2.0 日本語 Language Pack 
Visual C# 2005 Express Edition 
Microsoft SQL Server 2005 Express Edition x86";

            // Regex : 正規表現
            Regex myRegex = new Regex(@"[A-Z][a-z]+");
            // 対象文字列が存在するか?
            if (myRegex.IsMatch(str))
            {
                Console.WriteLine("// Match で一つだけ検索");
                // 10 文字目から 100 文字を対象に 検索 
                // Match は一個だけ
                Match myMatch = myRegex.Match(str,10,100);
                if (myMatch.Success)
                {
                    GroupCollection gc = myMatch.Groups;
                    Console.WriteLine("GroupCollection : {0} 個 Matchしました。", gc.Count);
                    for( int i =0; i<gc.Count;i++)
                    {
                        Console.WriteLine("GroupCollection value: {0}", gc[i].Value);

                    }

                    // 表示した後にもう一度検索して一つ目を表示
                    Match m = myMatch;
                    do
                    {
                        Console.WriteLine("{0}", m.Value);
                    } while ((m = m.NextMatch()).Success);
 
                }

                Console.WriteLine("// MatchCollection で全対象を検索");
                // MatchCollection で全対象を検索
                MatchCollection mc = myRegex.Matches(str);
                int cnt = mc.Count;
                if( cnt > 0)
                {
                    for (int i = 0; i < cnt; i++)
                    {
                        Match m = mc[i];
                        Console.WriteLine("{0} Length : {1}", i,m.Length);
                        Console.WriteLine("{0} Value : {1}", i,m.Value);
                        if (m.Length > 0)
                        {
                            // Console.WriteLine("{0} ToString() : {1}", i, m.ToString() );
                        }
                    }

                }
            }
        }

// Match で一つだけ検索
GroupCollection : 1 個 Matchしました。
GroupCollection value: Net
Net
Frameword
Microsoft
Net
Frameword
Language
Pack
Visual
Express
Edition
// MatchCollection で全対象を検索
0 Length : 9
0 Value : Microsoft
1 Length : 3
1 Value : Net
2 Length : 9
2 Value : Frameword
3 Length : 9
3 Value : Microsoft
4 Length : 3
4 Value : Net
5 Length : 9
5 Value : Frameword
6 Length : 8
6 Value : Language
7 Length : 4
7 Value : Pack
8 Length : 6
8 Value : Visual
9 Length : 7
9 Value : Express
10 Length : 7
10 Value : Edition
11 Length : 9
11 Value : Microsoft
12 Length : 6
12 Value : Server
13 Length : 7
13 Value : Express
14 Length : 7
14 Value : Edition

普通に検索できました。




4-18. 文字列操作 - 4 - 正規化 « 4. C# 入門 Level 2 » 4-20. 正規表現 / RegularExpressions - 2 - グループ


C# 入門 & 実践 / C sharp