[C#] 文字列から数値のみ抽出する

特定の文字列から数値のみ・英数字のみを抽出したい場合、正規表現を使って必要な文字以外を変換する。
以下を応用すると、必要な文字以外を別の文字に変換することも可能。
using System.Text.RegularExpressions;
using System.Diagnostics;

string s = "L1123452HZZ";
Regex re = new Regex(@"[^0-9]");
// 出力 : 1123452
Debug.WriteLine(re.Replace(s, ""));

string s2 = "ああああL1123452HZZ";
Regex re2 = new Regex(@"[^0-9a-zA-Z]");
// 出力 : L1123452HZZ
Debug.WriteLine(re2.Replace(s2, ""));

string s3 = "HあEあLあLあO";
Regex re3 = new Regex(@"[^0-9a-zA-Z]");
// 出力 : H_E_L_L_O
Debug.WriteLine(re3.Replace(s3, "_"));
Regex クラス - msdn
http://msdn.microsoft.com/ja-jp/library/system.text.regularexpressions.regex(v=vs.110).aspx

このブログの人気の投稿

コピーした行の挿入が表示されない時はフィルタされていないかチェック

Excel で一部の図形だけ固定する