如果我有这些字符串:

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

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


当前回答

在c# 7中,你可以内联out变量:

if(int.TryParse(str, out int v))
{
}

其他回答

我知道这是一个老线程,但是没有一个答案真的对我有用——要么效率低,要么没有被封装以便于重用。我还想确保它在字符串为空或null时返回false。在这种情况下,TryParse返回true(当解析为数字时,空字符串不会导致错误)。这是我的字符串扩展方法:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

使用简单:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

或者,如果你想测试其他类型的数字,你可以指定“样式”。 所以,要用指数转换一个数字,你可以使用:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

或者要测试一个潜在的十六进制字符串,你可以使用:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

可选的'culture'参数也可以以大致相同的方式使用。

它的限制是不能转换太大而不能包含在double类型中的字符串,但这是一个有限的要求,我认为如果你处理的数字比这个大,那么你可能需要额外的专门的数字处理函数。

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

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)
 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; 
    }

以防你不想用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;
    }
}

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

var numberString = "123";
int number;

int.TryParse(numberString , out number);

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