C# 十进制数的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/968825/
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
Regular expression for decimal number
提问by davorn
I need to validate a textbox
input and can only allow decimal inputs like: X,XXX
(only one digit before decimal sign and a precision of 3).
我需要验证textbox
输入,并且只能允许十进制输入,例如:(X,XXX
十进制符号前只有一位数字,精度为 3)。
I'm using C# and try this ^[0-9]+(\.[0-9]{1,2})?$
?
我正在使用 C# 并尝试这个^[0-9]+(\.[0-9]{1,2})?$
?
采纳答案by J-16 SDiZ
^[0-9]([.,][0-9]{1,3})?$
It allows:
它允许:
0
1
1.2
1.02
1.003
1.030
1,2
1,23
1,234
BUT NOT:
但不是:
.1
,1
12.1
12,1
1.
1,
1.2345
1,2345
回答by UnkwnTech
\d{1}(\.\d{1,3})?
Match a single digit 0..9 ?\d{1}?
Exactly 1 times ?{1}?
Match the regular expression below and capture its match into backreference number 1 ?(\.\d{1,3})??
Between zero and one times, as many times as possible, giving back as needed (greedy) ???
Match the character “.” literally ?\.?
Match a single digit 0..9 ?\d{1,3}?
Between one and 3 times, as many times as possible, giving back as needed (greedy) ?{1,3}?
Created with RegexBuddy
Matches:
1
1.2
1.23
1.234
比赛:
1
1.2
1.23
1.234
回答by Richard
There is an alternative approach, which does not have I18n problems (allowing ',' or '.' but not both): Decimal.TryParse
.
有一种替代方法,它没有 I18n 问题(允许 ',' 或 '.' 但不能同时出现):Decimal.TryParse
.
Just try converting, ignoring the value.
只需尝试转换,忽略值。
bool IsDecimalFormat(string input) {
Decimal dummy;
return Decimal.TryParse(input, out dummy);
}
This is significantly faster than using a regular expression, see below.
这比使用正则表达式要快得多,见下文。
(The overload of Decimal.TryParse
can be used for finer control.)
(Decimal.TryParse
可以使用的过载进行更精细的控制。)
Performance test results: Decimal.TryParse: 0.10277ms, Regex: 0.49143ms
性能测试结果:Decimal.TryParse:0.10277ms,Regex:0.49143ms
Code (PerformanceHelper.Run
is a helper than runs the delegate for passed iteration count and returns the average TimeSpan
.):
代码(PerformanceHelper.Run
是一个帮助程序,而不是为传递的迭代计数运行委托并返回平均值TimeSpan
。):
using System;
using System.Text.RegularExpressions;
using DotNetUtils.Diagnostics;
class Program {
static private readonly string[] TestData = new string[] {
"10.0",
"10,0",
"0.1",
".1",
"Snafu",
new string('x', 10000),
new string('2', 10000),
new string('0', 10000)
};
static void Main(string[] args) {
Action parser = () => {
int n = TestData.Length;
int count = 0;
for (int i = 0; i < n; ++i) {
decimal dummy;
count += Decimal.TryParse(TestData[i], out dummy) ? 1 : 0;
}
};
Regex decimalRegex = new Regex(@"^[0-9]([\.\,][0-9]{1,3})?$");
Action regex = () => {
int n = TestData.Length;
int count = 0;
for (int i = 0; i < n; ++i) {
count += decimalRegex.IsMatch(TestData[i]) ? 1 : 0;
}
};
var paserTotal = 0.0;
var regexTotal = 0.0;
var runCount = 10;
for (int run = 1; run <= runCount; ++run) {
var parserTime = PerformanceHelper.Run(10000, parser);
var regexTime = PerformanceHelper.Run(10000, regex);
Console.WriteLine("Run #{2}: Decimal.TryParse: {0}ms, Regex: {1}ms",
parserTime.TotalMilliseconds,
regexTime.TotalMilliseconds,
run);
paserTotal += parserTime.TotalMilliseconds;
regexTotal += regexTime.TotalMilliseconds;
}
Console.WriteLine("Overall averages: Decimal.TryParse: {0}ms, Regex: {1}ms",
paserTotal/runCount,
regexTotal/runCount);
}
}
回答by Rajesh
I just found TryParse()
has an issue that it accounts for thousands seperator. Example in En-US, 10,36.00 is ok. I had a specific scenario where the thousands seperator should not be considered and hence regex \d(\.\d)
turned out to be the best bet. Of course had to keep the decimal char variable for different locales.
我刚刚发现TryParse()
有一个问题,它占了数千个分隔符。以 En-US 为例,10,36.00 是可以的。我有一个特定的场景,不应该考虑千位分隔符,因此正则表达式\d(\.\d)
被证明是最好的选择。当然,必须为不同的语言环境保留十进制字符变量。
回答by rvanchis
As I tussled with this, TryParse in 3.5 does have NumberStyles: The following code should also do the trick without Regex to ignore thousands seperator.
当我对此争论不休时,3.5 中的 TryParse 确实具有 NumberStyles:以下代码也应该可以在没有 Regex 的情况下实现忽略数千个分隔符的技巧。
double.TryParse(length, NumberStyles.AllowDecimalPoint,CultureInfo.CurrentUICulture, out lengthD))
Not relevant to the original question asked but confirming that TryParse() indeed is a good option.
与最初提出的问题无关,但确认 TryParse() 确实是一个不错的选择。
回答by SK9
In general, i.e. unlimited decimal places:
一般来说,即无限的小数位:
^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$
^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$
回答by thomiel
In .NET, I recommend to dynamically build the regular expression with the decimal separator of the current cultural context:
在 .NET 中,我建议使用当前文化上下文的小数点分隔符动态构建正则表达式:
using System.Globalization;
...
NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
Regex re = new Regex("^(?\d+("
+ Regex.Escape(nfi.CurrencyDecimalSeparator)
+ "\d{1,2}))$");
You might want to pimp the regexp by allowing 1000er separators the same way as the decimal separator.
您可能希望通过允许 1000er 分隔符与小数分隔符相同的方式来拉条条正则表达式。