C# 判断一字符串是否为合法数字(正则表达式)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
/// <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);
}
/// 判断一个字符串是否为合法整数(不限制长度)
/// </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);
}