6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

定型ファイルを読み込んで、LINQで対象の行を抽出

Last updated at Posted at 2013-02-18

とりあえず 動いたので載せてみます。
悪い点がありましたら、教えて下さい。

ソース
// CSVファイルの読み込み
string[] lines = System.IO.File.ReadAllLines( strFilePath, enc );

// 正規表現で抽出する形を指定
Regex reg = new Regex( "\"(?<test>[0-9]{7}?)\"" );

// 対象の行を抽出
var targetLine = lines.Where( c => {
	// 正規表現にマッチしたか
	if( reg.IsMatch( c ) )
		// 判定対象位置がキーとマッチしたか。
		if( reg.Match( c ).Groups["test"].ToString() == key )
			return true;
	return false;
}).FirstOrDefault();

いただいたコメントを元に修正してみる 1

ソース
// CSVファイルの読み込み
IEnumerable<string> lines = System.IO.File.ReadLines( strFilePath, enc );

// 正規表現で抽出する形を指定
Regex reg = new Regex( "\"(?<test>[0-9]{7}?)\"" );

// 対象の行を抽出
var targetLine = lines
    .Where( c => reg.IsMatch( c ) )
    .FirstOrDefault( c => reg.Match( c ).Groups[ "test" ].ToString( ) == key );

だいぶ すっきり

6
6
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?