public static class StringHelper
{
//分數、帶分數
public static string sMatchNumInch = @"(([1-9]\d*-)?[1-9]\d*/[1-9]\d*|[1-9]\d*)""";
//數字
public static string sMatchNum = @"((-|)([1-9]+\d*|0)(\.\d+)?|0)";
//整數
public static string sMatchNumInt = @"((|-)[1-9]+(\d+)?|0)";
//正整數
public static string sMatchNumIntPositive = @"([1-9]+(\d+)?)";
//負整數
public static string sMatchNumIntNegative = @"(-[1-9]+(\d+)?)";
//非負整數
public static string sMatchNumIntNonNegative = @"([1-9]+(\d+)?|0)";
//非正整數
public static string sMatchNumIntNonPositive = @"(-[1-9]+(\d+)?|0)";
//正數
public static string sMatchNumPositive = @"(([1-9]+\d*)?((|0)\.\d+)?)";
//負數
public static string sMatchNumNegative = @"(-([1-9]+\d*|0)(\.\d+)?)";
//非負數
public static string sMatchNumNonNegative = @"(([1-9]+\d*)?((|0)\.\d+)?)";
//非正數
public static string sMatchNumNonPositive = @"(-([1-9]+\d*|0)(\.\d+)?|0)";
/// <summary>
/// 判斷字串是否是數字
/// </summary>
/// <param name="str"></param>
/// <param name="nt"></param>
/// <returns></returns>
/// <summary>
public static bool IsNumType(this string str, NumType nt)
{
if (str == "")
return false;
string matchString = "";
switch (nt)
{
case NumType.Number:
//數字
matchString = sMatchNum;
break;
case NumType.PositiveInt:
//正整數
matchString = sMatchNumIntPositive;
break;
case NumType.NonNegativeInt:
//非負整數(正整數 + 0)
matchString = sMatchNumIntNonNegative;
break;
case NumType.NonPositiveInt:
//非正整數(負整數 + 0)
matchString = sMatchNumIntNonPositive;
break;
case NumType.NegativeInt:
//負整數
matchString = sMatchNumIntNegative;
break;
case NumType.Int:
//整數
matchString = sMatchNumInt;
break;
case NumType.NonNegative:
//非負數(正數 + 0)
matchString = sMatchNumNonNegative;
break;
case NumType.Positive:
//正數
matchString = sMatchNumPositive;
break;
case NumType.NonPositive:
//非正數(負數 + 0)
matchString = sMatchNumNonPositive;
break;
case NumType.Negative:
//負數
matchString = sMatchNumNegative;
break;
default:
break;
}
return Regex.IsMatch(str, matchString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 第1位:9表示"非",1表示"數",2表示"整數"
/// 末位:1表示正,0表示負
/// </summary>
public enum NumType
{
/// <summary>
/// 浮點數
/// </summary>
Number = 1,
/// <summary>
/// 整數
/// </summary>
Int = 2,
/// <summary>
/// 正數
/// </summary>
Positive = 11,
/// <summary>
/// 負數
/// </summary>
Negative = 10,
/// <summary>
/// 正整數
/// </summary>
PositiveInt = 21,
/// <summary>
/// 負整數
/// </summary>
NegativeInt = 20,
/// <summary>
/// 非正數
/// </summary>
NonPositive = 911,
/// <summary>
/// 非負數
/// </summary>
NonNegative = 910,
/// <summary>
/// 非正整數
/// </summary>
NonPositiveInt = 921,
/// <summary>
/// 非負整數
/// </summary>
NonNegativeInt = 920,
}
}