C# 正则表达式以允许一个带有一个点或逗号的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15412658/
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-10 16:44:19  来源:igfitidea点击:

Regular expression to allow a number with one dot or comma in it

c#regex

提问by MMM

Could any of you help me with a regular expression which will accept these:

你们中的任何人都可以帮助我使用一个可以接受这些的正则表达式:

1112312.2312312
1.23123
1,231
1.2344
123.123
123123

...but not these:

...但不是这些:

.1123
,2313
123.231.32
123..12

采纳答案by MMM

Update:

更新:

This solution will match the updated requirements:

此解决方案将匹配更新的要求:

^\d+(?:[\.\,]\d+)?$


Here is a basic expression that allows only one dot or comma, and requires the rest of the expression to be digits.

这是一个基本表达式,只允许一个点或逗号,并且要求表达式的其余部分为数字。

^\d*[\.\,]\d*$

This would also match just .or just ,, even if there were no digits.

即使没有数字,这也将匹配 just.或 just ,

If you want to require at least one digit on each side of the dot or comma, use this:

如果您想在点或逗号的每一侧至少要求一个数字,请使用:

^\d+[\.\,]\d+$

(I think that is the one you want, based on your sample data).

(根据您的样本数据,我认为这是您想要的)。

If you only need to require at least one digit total, use this (using look-ahead):

如果您只需要至少一位总数,请使用此(使用前瞻):

^(?=.*\d)\d*[\.\,]\d*$

This would also make the dot/comma optional:

这也将使点/逗号可选:

^(?=.*\d)\d*[\.\,]?\d*$

回答by Oliver

This should do the trick:

这应该可以解决问题:

var test = new Regex(@"^\d+([\.\,]?\d+)?$");

Usage:

用法:

bool isValid = test.IsMatch("1.1"); //true