【发布时间】:2010-11-12 17:38:34
【问题描述】:
考虑在 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;}
}
问题:如何改进以使正则表达式匹配负数和小数?您会做出哪些根本性的改进?
【问题讨论】:
-
负数和小数只是冰山一角。
-
什么会在 try 块中抛出 FormatException?