C# 十进制值的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11431945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:50:55  来源:igfitidea点击:

Regular Expression For Decimal Value

c#regex

提问by Maverick

I want a regular expression for decimal input, which can take 4 digits before decimal or comma and 2 digits after decimal/comma. 5 digit number without decimal is invalid. Also can accept null.

我想要一个十进制输入的正则表达式,它可以在小数点或逗号之前取 4 位数字,在小数点/逗号之后取 2 位数字。不带小数的 5 位数字无效。也可以接受空值。

Correct Values can be:

正确的值可以是:

1, 1111, 2222.56, 0.99, 9999.5

1、1111、2222.56、0.99、9999.5

Invalid

无效的

88888, 8.888,

88888, 8.888,

Validation show also include comma along with decimal.

验证显示还包括逗号和小数点。

If possible, then also explain the expression.

如果可能,还要解释表达式。

采纳答案by Ria

Regex.IsMatch(strInput, @"[\d]{1,4}([.,][\d]{1,2})?");

and explain:

并解释:

[\d]{1,4}    any character of: digits (0-9) between 1 and 4 times

[.,]         any character of: '.', ','

[\d]{1,2}    any character of: digits (0-9) between 1 and 2 times

(...)?       match the expression or not (zero or one)

回答by Jirka Hanika

[0-9]{1,4}(\.[0-9]{1,2})?

This means, 1 to 4 digits, and then optionally both a decimal point and 1 to 2 digits.

这意味着,1 到 4 位数字,然后是可选的小数点和 1 到 2 位数字。

回答by burning_LEGION

use this regex \d{4}[,\.]\d{2}or \d+([,\.]\d+)?for any decimal

使用此正则表达式\d{4}[,\.]\d{2}\d+([,\.]\d+)?任何小数

回答by Seenivasan

We can do code for checking Stirng value contains Decimal points by following code

我们可以通过以下代码来做检查Stirng值是否包含小数点的代码

    Dim Success As Boolean
    If text.Contains(".") Then
        Dim result As Integer = Split(text, ".")(1)
        If result > 0 Then
            Success = True      'Containing Decimal Points greater than
        Else
            Success = False     'Containing "0" as Decimal Points 
        End If
    End If
    Return Success

回答by JacekT

^-?(0|[1-9]\d{0,3})([,\.]\d{1,2})?$

BEFORE COMMA:

逗号前:

^ - beginning of the string

^ - 字符串的开头

-? - there may be zero or one negative sign

-?- 可能有零或一个负号

0 - decimal may starts with only single zero at the beginning...

0 - 十进制可以只以一个零开头...

| - or ...

| - 或者 ...

[1-9] - with any digit from 1 to 9

[1-9] - 1 到 9 之间的任何数字

\d{0,3} - followed by any 3 digits

\d{0,3} - 后跟任意 3 位数字

AFTER COMMA:

逗号后:

[,.] - there may be "," or "."

[,.] - 可能有“,”或“.”

\d{1,2} - followed by 1 or 2 digits

\d{1,2} - 后跟 1 或 2 位数字

(...)? - zero or one time

(……)?- 零次或一次

$ - end of the string

$ - 字符串的结尾