正则表达式几乎完美的数值

Dan*_*n B 18 c# regex

我有这个REGEX 几乎完美......它似乎处理除了带负号然后是小数的数字之外的所有内容.所以,如果我输入:

-.2
Run Code Online (Sandbox Code Playgroud)

我收到一个错误 -

这是我的正则表达式 - 我测试过的其他所有内容都完美无缺...

^(\+|-)?[0-9]{1,11}?(?:\.[0-9]{1,4})?$
Run Code Online (Sandbox Code Playgroud)

这允许:

  • 最多11位数(99亿)
  • 正数或负数
  • 最多4位小数(可选)
  • 小数点前的前导0是可选的 - 仅适用于正数

这一切都有效:

-0.2345
-10
12
.125
0.1245
5.555
25000000000 (aka 25 Billion)
25000000000.25 
Run Code Online (Sandbox Code Playgroud)

这些不起作用:

-.2
-.421
Run Code Online (Sandbox Code Playgroud)

eno*_*l76 20

正则表达式可能很昂贵...为什么不使用Decimal.Parse或Float.parse?

您当前的实现将无法使用备用数字样式,例如欧洲.(点)和,(逗号)互换...而Decimal.Parse将:

string stringValue = "45.889,33";
CultureInfo currentCulture = Thread.CurrentCulture; //set this way up in the execution chain
decimal thenumber = Decimal.Parse(stringValue, currentCulture);
//thenumber = 45889.33 in us-en display format.
Run Code Online (Sandbox Code Playgroud)

数值解析不是正则表达式,IMO的一个很好的应用程序.

  • 您的答案也比正则表达式更容易理解 - 因此代码将更容易维护 (2认同)

Joh*_*pit 9

试试这个:

^(\+|-)?[0-9]{0,11}?(?:\.[0-9]{1,4})?$
Run Code Online (Sandbox Code Playgroud)

更新:

上述正则表达式接受字符串+,- (the empty string). You can use a lookahead to restrict those. The lookahead ensures there must be a character after the +-符号.

正确的解决方案是:

^(\+|-)?(?=.{1})[0-9]{0,11}(?:\.[0-9]{1,4})?$
Run Code Online (Sandbox Code Playgroud)

一个工作的例子:

字符串接受:

-0.2345
-10
12
.125
0.1245
5.555
-.2
-.421
Run Code Online (Sandbox Code Playgroud)

字符串不被接受:

100000000000.0001
+
-

123456789012
1111111111.12345
+1.11.1
-2.
Run Code Online (Sandbox Code Playgroud)