C#判断一个string是否为数字

1.正则表达式
A.

using System;
using System.Text.RegularExpressions;

public bool IsNumber(String strNumber)
{
Regex objNotNumberPattern
=new Regex("[^0-9.-]");
Regex objTwoDotPattern
=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
Regex objTwoMinusPattern
=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
String strValidRealPattern
="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
String strValidIntegerPattern
="^([-]|[0-9])[0-9]*$";
Regex objNumberPattern 
=new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");

return !objNotNumberPattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber) &&
!objTwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);
}

B.

public static bool IsNumeric(string value)
{
return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
}
public static bool IsInt(string value)
{
return Regex.IsMatch(value, @"^[+-]?\d*$");
}
public static bool IsUnsign(string value)
{
return Regex.IsMatch(value, @"^\d*[.]?\d*$");
}

2.遍历

public bool isnumeric(string str)
{
    
char[] ch = new char[str.Length];
    ch 
= str.ToCharArray();
    
for (int i = 0; i < ch.Length; i++)
    {
        
if (ch[i] < 48 || ch[i] > 57)
            
return true//非数字
    }
    
return false//数字
}

 

posted on 2009-11-06 20:26  cnfi  阅读(550)  评论(2编辑  收藏  举报