/**//// <summary>
/// 判斷一個字串是否為合法整數(不限制長度)
/// </summary>
/// <param name="s">字串</param>
/// <returns></returns>
public static bool IsInteger(string s)
{
string pattern = @"^\d*$";
return Regex.IsMatch(s,pattern);
}
/**//// <summary>
/// 判斷一個字串是否為合法數字(0-32整數)
/// </summary>
/// <param name="s">字串</param>
/// <returns></returns>
public static bool IsNumber(string s)
{
return IsNumber(s,32,0);
}
/**//// <summary>
/// 判斷一個字串是否為合法數字(指定整數位元和小數位元)
/// </summary>
/// <param name="s">字串</param>
/// <param name="precision">整數位元</param>
/// <param name="scale">小數位元</param>
/// <returns></returns>
public static bool IsNumber(string s,int precision,int scale)
{
if((precision == 0)&&(scale == 0))
{
return false;
}
string pattern = @"(^\d{1,"+precision+"}";
if(scale>0)
{
pattern += @"\.\d{0,"+scale+"}$)|"+pattern;
}
pattern += "$)";
return Regex.IsMatch(s,pattern);
}
如果還能允許負數,則在各個 " ^ " 後面加上 " -? " 即可。