1
1

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.

【C#】正規表現で抽出した結果に対してLinqを使う

Last updated at Posted at 2019-09-03

正規表現を使って条件に一致する文字を抽出して
その結果を処理したい時にそのままだとLinqが使えなかったのでメモ。

任意の文字列から16進数として有効な文字を2文字ずつ取得したい場合のサンプル。

16進文字列を抽出
// 抽出結果を格納したい
var result = new List<string>();

// 16進数文字列を2文字ずつ取得
var matches = Regex.Matches("0123abcdXyx", "[0-9a-fA-F]{2}");

// MatchCollectionクラスはIEnumerableでIEnumerable<T>じゃないので
// そのままだとLinqが使えないのでIEnumerable<Match>にキャストしてから使う。
result.AddRange(matches.Cast<Match>().Select(m => m.Value));

// 結果は『01』『23』『ab』『cd』

1
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?