C# 正規表現の基礎をメモ
Regexクラス
・C#で正規表現を使う場合はRegexを使う。
・コンストラクタでパターン文字列を指定する。
・IsMatch(String)メソッド(戻り値bool)で正規表現と一致するかどうかを取得する。
使用例
以下簡単な使用例、行頭、行末、繰り返しを組み合わせれば業務アプリの入力チェックを簡素に記述出来ると思われる。
よく見かけるのは銀行系の利用可能文字、電話番号、郵便番号、金額や単価、数量とかかな。
// 空文字または半角英数字のみ Assert.IsTrue(new Regex("^[a-zA-Z0-9]*$").IsMatch(string.Empty)); Assert.IsTrue(new Regex("^[a-zA-Z0-9]*$").IsMatch("azAZ09")); Assert.IsFalse(new Regex("^[a-zA-Z0-9]*$").IsMatch("azAZ09あ")); Assert.IsFalse(new Regex("^[a-zA-Z0-9]*$").IsMatch("a-0")); // 3桁半角英数字のみ Assert.IsTrue(new Regex("^[a-zA-Z0-9]{3}$").IsMatch("A12")); Assert.IsTrue(new Regex("^[a-zA-Z0-9]{3}$").IsMatch("9ab")); Assert.IsFalse(new Regex("^[a-zA-Z0-9]{3}$").IsMatch("dz")); Assert.IsFalse(new Regex("^[a-zA-Z0-9]{3}$").IsMatch("9abc")); // 3桁以下半角英数字のみ Assert.IsTrue(new Regex("^[a-zA-Z0-9]{0,3}$").IsMatch(string.Empty)); Assert.IsTrue(new Regex("^[a-zA-Z0-9]{0,3}$").IsMatch("9ab")); Assert.IsTrue(new Regex("^[a-zA-Z0-9]{0,3}$").IsMatch("Aa")); Assert.IsFalse(new Regex("^[a-zA-Z0-9]{0,3}$").IsMatch("9abc")); Assert.IsFalse(new Regex("^[a-zA-Z0-9]{0,3}$").IsMatch("9abc"));