C# 有限小数的正则表达式
这里是正则表达式语法的新特性。尝试编写正则表达式以提供一些输入验证 我需要的是一个正则表达式来匹配一个整数,或者一个小数点后正好有一位数字的小数点C# 有限小数的正则表达式,c#,regex,C#,Regex,这里是正则表达式语法的新特性。尝试编写正则表达式以提供一些输入验证 我需要的是一个正则表达式来匹配一个整数,或者一个小数点后正好有一位数字的小数点 Good Match 1 12 100 1.1 100.1 1.0 No Match 1.22 1. 0 012 以下是我的想法,但它不起作用: Regex.IsMatch(paidHours, "\\d+[.]?[0-9]?") 您可以尝试以下方法: Regex.IsMatch(paidHours, "^\\d+(\\.\\d)?$") 您
Good Match
1
12
100
1.1
100.1
1.0
No Match
1.22
1.
0
012
以下是我的想法,但它不起作用:
Regex.IsMatch(paidHours, "\\d+[.]?[0-9]?")
您可以尝试以下方法:
Regex.IsMatch(paidHours, "^\\d+(\\.\\d)?$")
您可以尝试以下方法:
Regex.IsMatch(paidHours, "^\\d+(\\.\\d)?$")
编辑OP问题后编辑答案。
Regex.IsMatch(paidHours, @"^[1-9][0-9]*(\.[0-9])?$");
说明:
^ : Start of the String
[1-9] : A single number between 1 and 9
[0-9]* : Zero or more number(s) between 0 and 9
([0-9]? would match zero or one number and the String "100" would not match the regex)
( : Start of a group
\. : A point
[0-9] : A single number between 0 and 9
)? : End of the group. The group must be repeated zero or one time
$ : End of the String
请注意,
\d
并不完全等同于[0-9]
:\d
匹配任何。例如,这个字符௮如果您使用\d
将匹配code>,但如果您使用[0-9]
编辑操作问题编辑后的答案,则不会匹配code>。
Regex.IsMatch(paidHours, @"^[1-9][0-9]*(\.[0-9])?$");
Regex.IsMatch(paidHours, @"^\d+(\.\d)?$")
说明:
^ : Start of the String
[1-9] : A single number between 1 and 9
[0-9]* : Zero or more number(s) between 0 and 9
([0-9]? would match zero or one number and the String "100" would not match the regex)
( : Start of a group
\. : A point
[0-9] : A single number between 0 and 9
)? : End of the group. The group must be repeated zero or one time
$ : End of the String
请注意,\d
并不完全等同于[0-9]
:\d
匹配任何。例如,这个字符௮如果您使用\d
将匹配code>,但如果您使用[0-9]
请尝试指定行尾:
Regex.IsMatch(paidHours, @"^\d+(\.\d)?$")
@"^\d+[.]?[0-9]?$"
由于ie 1.234与ie 1.2匹配,因此您的正则表达式无法工作,如果您不指定希望字符串以“$”符号结尾。请尝试指定行尾:
@"^\d+[.]?[0-9]?$"
由于ie 1.234与1.2匹配,如果不指定字符串以'$'
符号结尾,您的正则表达式将无法工作。@Otiel是否确定不需要转义
?@Otiel:您需要转义,否则它也将匹配!\^&*()
etc.@Y.Shoham:是的,你说得对,我把括号()
和括号[]
规则搞混了。编辑了答案。非常好,谢谢。我忘了在0或012上包含“不匹配”的要求(参见上面的编辑)。我试图将开头改为^[1-9],但当然它在10或20等位置上不匹配。@EkoostikMartin:请参阅我编辑中的解释。不客气:)@Otiel您确定没有必要转义
?@Otiel:您确实需要转义,否则它也会匹配!@$%^&*()
etc.@Y.Shoham:是的,你说得对,我把括号()
和括号[]
规则搞混了。编辑了答案。非常好,谢谢。我忘了在0或012上包含“不匹配”的要求(参见上面的编辑)。我试图将开头改为^[1-9],但当然它在10或20等位置上不匹配。@EkoostikMartin:请参阅我编辑中的解释。不客气:)+1的模式。我鼓励您添加锚,以避免模式可能出现的a1.11bc
+1。我鼓励您添加锚,以避免可能的a1.11bc
。