28,391
社区成员
发帖
与我相关
我的任务
分享
#region 用正则判断是否匹配特定字符
public static bool isMatch(string val, string reg)
{
if (val == null || val == "")
return false;
return new Regex(reg).IsMatch(val);
}
#endregion
#region 判断给定的字符串(strNumber)是否是数值型,可以是小数点、负数,小数点前允许有20位数字,小数点后也一样
public static bool isNumber(string val)
{
return new Regex(@"^-?\d{1,20}(\.\d{1,20})?$").IsMatch(val);
}
//是否整数(包括正整数、负整数、0,限制在20个字符以内)
public static bool isInt(string val)
{
return new Regex(@"^-?\d{1,20}$").IsMatch(val);
}
#endregion
#region object型转换为int型
public static int strToInt(object strValue, int defValue)
{
//defValue为无法转换成int型的时候返回的默认值
if (strValue != null)
{
if (isInt(strValue.ToString().Trim()))
{
//如果是由数字组成的字符串,强制转换成int型,否则就返回defValue的值
defValue = Convert.ToInt32(strValue);
}
}
return intValue;
}
#endregion
//另外,可能还会有纯数字、字母、下划线组成的参数,那么用以下方法判断
public static bool isLetter(string val)
{
return new Regex(@"^\w{1,20}$").IsMatch(val);
}
//有时候还会需要0,1,2,3或者0,1,2,3,这种格式的参数,那么用以下方法判断
public static bool isSafeString(string val, int maxLength)
{
//参数maxLength为限定的字符串长度
if(val.Length>maxLength) return false;//超过指定的长度,直接返回false
return new Regex(@"^(\d{1,20},)*\d{1,20},?$").IsMatch(val);
}
//你还需要纯中文的参数?那么自己写吧...
//最后:新年快乐 ^_^