如果我有这些字符串:

"abc" =假 "123" =真 "ab2" = false

是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?


当前回答

试试下面定义的正则表达式

new Regex(@"^\d{4}").IsMatch("6")    // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg")
new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)

其他回答

如果你想知道一个字符串是否是一个数字,你可以尝试解析它:

var numberString = "123";
int number;

int.TryParse(numberString , out number);

注意,TryParse返回一个bool值,您可以使用它来检查解析是否成功。

以防你不想用int。解析或双重。解析,你可以用这样的东西来滚动你自己的:

public static class Extensions
{
    public static bool IsNumeric(this string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c) && c != '.')
            {
                return false;
            }
        }

        return true;
    }
}
 bool is_number(string str, char delimiter = '.')
    {
        if(str.Length==0) //Empty
        {
            return false;
        }
        bool is_delimetered = false;
        foreach (char c in str)
        {
            if ((c < '0' || c > '9') && (c != delimiter)) //ASCII table check. Not a digit && not delimeter
            {
                return false;
            }
            if (c == delimiter)
            {
                if (is_delimetered) //more than 1 delimiter
                {
                    return false;
                }
                else //first time delimiter
                {
                    is_delimetered = true;
                }
            }
        }
        return true; 
    }
public static bool IsNumeric(this string input)
{
    int n;
    if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
    {
        foreach (var i in input)
        {
            if (!int.TryParse(i.ToString(), out n))
            {
                return false;
            }

        }
        return true;
    }
    return false;
}

翻倍。TryParse

bool Double.TryParse(string s, out double result)