「C#」文字列が半角英数字のみかチェックする

書式
半角英数チェックの正規表現式
^[a-zA-Z0-9]+$
正規表現を利用して指定された文字列が半角英数のみかチックします。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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]+$");
}
}
}
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]+$"); } } }
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]+$");
   }
  }
}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
True
True
False
False
False
False
True True False False False False
True
True
False
False
False
False

 

C#

Posted by arkgame