.NET测试字符串的数值

p.c*_*ell 4 c# regex algorithm

考虑在C#中需要一个函数来测试字符串是否是数值.

要求:

  • 必须返回一个布尔值.
  • 函数应该能够允许整数,小数和负数.
  • 假设没有using Microsoft.VisualBasic打电话IsNumeric().这是一个重新发明轮子的情况,但运动很好.

目前的实施:

 //determine whether the input value is a number
    public static bool IsNumeric(string someValue)
    {
        Regex isNumber = new Regex(@"^\d+$");
        try
        {
            Match m = isNumber.Match(someValue);
            return m.Success;                           
        }
        catch (FormatException)
        {return false;}
    }
Run Code Online (Sandbox Code Playgroud)

问题:如何改进,以便正则表达式匹配负数和小数?你做的任何根本改进?

Sau*_*tka 19

就在我的头顶 - 为什么不使用double.TryParse?我的意思是,除非你真的想要一个正则表达式解决方案 - 在这种情况下我不确定你真的需要:)


Amy*_*Amy 10

你能用到.TryParse吗?

int x;
double y;
string spork = "-3.14";

if (int.TryParse(spork, out x))
    Console.WriteLine("Yay it's an int (boy)!");
if (double.TryParse(spork, out y))
    Console.WriteLine("Yay it's an double (girl)!");
Run Code Online (Sandbox Code Playgroud)


Sea*_*ght 6

Regex isNumber = new Regex(@"^[-+]?(\d*\.)?\d+$");
Run Code Online (Sandbox Code Playgroud)

更新为允许在数字前面加上+或 - .

编辑:您的try块没有做任何事情,因为其中的任何方法实际上都没有FormatException.整个方法可以写成:

// Determine whether the input value is a number
public static bool IsNumeric(string someValue)
{
  return new Regex(@"^[-+]?(\d*\.)?\d+$").IsMatch(someValue);
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这有土耳其测试问题(请参阅http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html上的#4) (4认同)