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)
问题:如何改进,以便正则表达式匹配负数和小数?你做的任何根本改进?
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)
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)