「C#」文字列が半角英数字のみかチェックする
書式
半角英数チェックの正規表現式
^[a-zA-Z0-9]+$
正規表現を利用して指定された文字列が半角英数のみかチックします。
使用例
using System;
using System.Text.RegularExpressions;
namespace TestDemo
{
class Program
{
static void Main(string[] args)
{ //英字数値
bool a = isFunc("studyDEF989");
Console.WriteLine(a);
//数字
bool b = isFunc("678");
Console.WriteLine(b);
//特殊文字
bool c = isFunc("@#$?!");
Console.WriteLine(c);
//日本語文字列
bool d = isFunc("テスト");
Console.WriteLine(d);
//null
bool e = isFunc(null);
Console.WriteLine(e);
//空白
bool f = isFunc("");
Console.WriteLine(f);
}
//半角英数字チェック関数
public static bool isFunc(string str)
{
// nullの場合はfalseを返す
if (str == null)
{
return false;
}
// 半角英数チェック
return Regex.IsMatch(str, @"^[a-zA-Z0-9]+$");
}
}
}
実行結果
True True False False False False