正则表达式来验证。net的非负小数还是空?

时间:2022-09-11 21:48:28

I'm looking for a regular expression that would validate a non-negative decimal (.NET type), i.e. if a non-negative value can be parsed using decimal.Parse(...), it should be considered valid. Otherwise invalid.

我正在寻找一个正则表达式来验证非负的小数(。NET类型),即如果一个非负值可以使用decimal.Parse(…)进行解析,则应该认为它是有效的。否则无效。

I'm okay if it fails the 28-29 significant digits validation - relying on user's sanity here - and then we have another validation layer that would catch it anyway.

如果它没有通过28-29位有效数字验证(这里依赖于用户的健全程度),那么我没问题,然后我们就有了另一个验证层,无论如何都可以捕获它。

Here is what I came up with:

以下是我的想法:

^(?:[1-9]\d*|0)?(?:\.\d+)?$

Problem is that it rejects 1. which is a valid number (you can verify from the immediate window in VS). Could be other edge cases I did not test. Please advise.

问题是它拒绝1。这是一个有效的数字(您可以从VS中的直接窗口验证)。可能是我没有测试的其他边缘情况。请建议。

P.S. I included ASP.NET and C# tags because this is for a web application written in C#, in which this regular expression is passed to a 3rd party component, which then works on the client (i.e. JS), so I cannot easily put custom code there (i.e. decimal.TryParse or smth like that).

注:我包括ASP。NET和c#标签,因为这是一个用c#编写的web应用程序,其中这个正则表达式被传递给第三方组件,然后在客户端(即JS)上工作,所以我不能轻易地在那里放置自定义代码(即decimal)。尝试解析或smth,像那样)。

1 个解决方案

#1


3  

You can use this regex based on a negative lookahead to avoid matching single dot:

你可以使用这个正则表达式来避免匹配单个点:

^(?!\D+$)\+?\d*?(?:\.\d*)?$
  • (?!\D+$) is negative lookahead to assert failure when input is non digit characters
  • (?!\D+$)当输入为非数字字符时,为负前视以断言失败
  • ?:\.\d*)? allows for matching 123. type of number.
  • :\ \ d *)?123年允许匹配。类型的数。

RegEx Demo 1

RegEx演示1

RegEx Demo 2

RegEx演示2

#1


3  

You can use this regex based on a negative lookahead to avoid matching single dot:

你可以使用这个正则表达式来避免匹配单个点:

^(?!\D+$)\+?\d*?(?:\.\d*)?$
  • (?!\D+$) is negative lookahead to assert failure when input is non digit characters
  • (?!\D+$)当输入为非数字字符时,为负前视以断言失败
  • ?:\.\d*)? allows for matching 123. type of number.
  • :\ \ d *)?123年允许匹配。类型的数。

RegEx Demo 1

RegEx演示1

RegEx Demo 2

RegEx演示2