Identify if a string is a number

前端 未结 25 3344
無奈伤痛
無奈伤痛 2020-11-22 00:13

If I have these strings:

  1. \"abc\" = false

  2. \"123\" = true

  3. \"ab2\"

25条回答
  •  春和景丽
    2020-11-22 00:20

    If you want to catch a broader spectrum of numbers, à la PHP's is_numeric, you can use the following:

    // From PHP documentation for is_numeric
    // (http://php.net/manual/en/function.is-numeric.php)
    
    // Finds whether the given variable is numeric.
    
    // Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
    // exponential part. Thus +0123.45e6 is a valid numeric value.
    
    // Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
    // only without sign, decimal and exponential part.
    static readonly Regex _isNumericRegex =
        new Regex(  "^(" +
                    /*Hex*/ @"0x[0-9a-f]+"  + "|" +
                    /*Bin*/ @"0b[01]+"      + "|" + 
                    /*Oct*/ @"0[0-7]*"      + "|" +
                    /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + 
                    ")$" );
    static bool IsNumeric( string value )
    {
        return _isNumericRegex.IsMatch( value );
    }
    

    Unit Test:

    static void IsNumericTest()
    {
        string[] l_unitTests = new string[] { 
            "123",      /* TRUE */
            "abc",      /* FALSE */
            "12.3",     /* TRUE */
            "+12.3",    /* TRUE */
            "-12.3",    /* TRUE */
            "1.23e2",   /* TRUE */
            "-1e23",    /* TRUE */
            "1.2ef",    /* FALSE */
            "0x0",      /* TRUE */
            "0xfff",    /* TRUE */
            "0xf1f",    /* TRUE */
            "0xf1g",    /* FALSE */
            "0123",     /* TRUE */
            "0999",     /* FALSE (not octal) */
            "+0999",    /* TRUE (forced decimal) */
            "0b0101",   /* TRUE */
            "0b0102"    /* FALSE */
        };
    
        foreach ( string l_unitTest in l_unitTests )
            Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );
    
        Console.ReadKey( true );
    }
    

    Keep in mind that just because a value is numeric doesn't mean it can be converted to a numeric type. For example, "999999999999999999999999999999.9999999999" is a perfeclty valid numeric value, but it won't fit into a .NET numeric type (not one defined in the standard library, that is).

提交回复
热议问题