decimal.Parse 接受的小数正则表达式

Regular expression for decimals that are accepted in decimal.Parse

期望的结果是一种正输入模式,它不会在 decimal.Parse 中抛出异常并且不接受 01 类模型输入。

有效输入:

1
1.2
.2
1.

无效输入:

01
01.2
.
1.B
A.2
A
A.

我喜欢这个 answer (-?(0|([1-9]\d*))(\.\d+)?); but somehow (as mentioned in the comment), it accepts X.2 (only with Regex.IsMatch) and negative decimals, and rejects 1.; so I modified it to /((0|([1-9]\d*))(\.\d*)?)|(\.\d+)/g, and it worked perfectly in regexr.com and also RegExr v1 中的图案;但我没有运气 Regex.IsMatch.

有什么建议吗?为什么该模式在其他地方有效时却不能与 Regex.IsMatch 一起使用?

这通过了你所有的测试:

var reg = new Regex("^(([1-9]*[0-9](\.|(\.[0-9]*)?))|(\.[0-9]+))$");

(reg.IsMatch("1") == true).Dump();
(reg.IsMatch("1.2") == true).Dump();
(reg.IsMatch(".2") == true).Dump();
(reg.IsMatch("1.") == true).Dump();

(reg.IsMatch("01") == false).Dump();
(reg.IsMatch("01.2") == false).Dump();
(reg.IsMatch(".") == false).Dump();
(reg.IsMatch("1.B") == false).Dump();
(reg.IsMatch("A.2") == false).Dump();
(reg.IsMatch("A") == false).Dump();
(reg.IsMatch("A.") == false).Dump();

解释:

我们会尽可能多地捕获 1-9 的数字。这不包括前导 0。然后我们允许小数点前的任何数字。

那么我们有三种情况:没有小数点,有小数点,小数点后有数字。

否则,如果我们以小数点开头,我们允许任何数字,但至少在小数点后一个。这不包括 .

您必须删除开头的“/”字符。因为在Javascript/ECMAScript而不是c#中指定正则表达式的开始是正则表达式的语法。(参考:What does the forward slash mean within a JavaScript regular expression?)因此,最终的正则表达式是

((0|([1-9]\d*))(\.\d*)?)|(\.\d+)/g

我想这个简单的正则表达式应该可以很好地完成工作/-?(0?\.\d+|[1-9]\d*\.?\d*)/g

你没有要求它,但它也处理底片。如果不需要,只需删除开头的 -? 并使其更简单。