nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

C#でファイルから一行ずつ読み出し、正規表現を使って文字列を検索し、抽出する [C#]

C#で、ファイルから一行ずつ読み出し、文字列を検索し、抽出する方法はいくつかありますが、正規表現を使う方法が一般的です。

以下に、ファイルから一行ずつ読み出し、正規表現を使って文字列を検索し、抽出するプログラムを記載します。

D:\test.txtに以下のようなファイルがある場合において、1行ずつ文字列を読み出します。読み出す処理は、最終行まで繰り返し実施します。 正規表現パターンrgxが、読みだした文字列に存在するかどうか、Matchオブジェクトの Successプロパティの値を確認して判断します。 一致が見つかった場合、返された Match オブジェクトの Value プロパティから部分文字列が含まれています。 一致が検出されない場合、値は String.Emptyです。

test1
test2
test3
test4
test5
using System;
using System.Text.RegularExpressions;

namespace LogRead
{
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate the regular expression object.
            Regex rgx = new Regex(@"test3", RegexOptions.IgnoreCase);

            using (System.IO.StreamReader file = new System.IO.StreamReader(@"D:\test.txt", System.Text.Encoding.ASCII))
            {
                string line = "";

                while ((line = file.ReadLine()) != null)
                {
                    if (rgx.Match(line).Success)
                    {
                        Console.WriteLine(line);
                        System.Diagnostics.Debug.WriteLine(line);
                    }
                }
            }

            System.Console.ReadLine();
        }
    }
}

ただし、上記の場合では、例えば、ファイルが見つからない場合は、例外が発生してしまいます。 f:id:nprogram:20171003233520p:plain

そのような場合は、try catch節を用いるとよいでしょう。

using System;
using System.Text.RegularExpressions;

namespace LogRead
{
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate the regular expression object.
            Regex rgx = new Regex(@"test3", RegexOptions.IgnoreCase);

            try
            {
                using (System.IO.StreamReader file = new System.IO.StreamReader(@"D:\test.tst", System.Text.Encoding.ASCII))
                {
                    string line = "";

                    while ((line = file.ReadLine()) != null)
                    {
                        if (rgx.Match(line).Success)
                        {
                            Console.WriteLine(line);
                            System.Diagnostics.Debug.WriteLine(line);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }

            System.Console.ReadLine();
        }
    }
}

以下のように、エラー内容を取得することができました。

f:id:nprogram:20171003235219p:plain

環境について

  • IDE : Microsoft Visual Studio Community 2017
  • プロジェクト : C# コンソールアプリケーション