我需要验证textbox
输入,并且只能允许十进制输入,如:( X,XXX
十进制符号前只有一位数,精度为3).
我正在使用C#试试这个^[0-9]+(\.[0-9]{1,2})?$
?
J-1*_*DiZ 55
^[0-9]([.,][0-9]{1,3})?$
Run Code Online (Sandbox Code Playgroud)
它允许:
0
1
1.2
1.02
1.003
1.030
1,2
1,23
1,234
Run Code Online (Sandbox Code Playgroud)
但不是:
.1
,1
12.1
12,1
1.
1,
1.2345
1,2345
Run Code Online (Sandbox Code Playgroud)
Ric*_*ard 21
还有另外一种方法,它不具有本地化和全球化问题(允许""或者但不能同时"") Decimal.TryParse
.
试试转换,忽略价值.
bool IsDecimalFormat(string input) {
Decimal dummy;
return Decimal.TryParse(input, out dummy);
}
Run Code Online (Sandbox Code Playgroud)
这比使用正则表达式快得多,见下文.
(过载Decimal.TryParse
可用于更精细的控制.)
性能测试结果:Decimal.TryParse:0.10277ms,正则表达式:0.49143ms
代码(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);
}
}
Run Code Online (Sandbox Code Playgroud)
\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
Run Code Online (Sandbox Code Playgroud)
比赛:
1
1.2
1.23
1.234
归档时间: |
|
查看次数: |
118162 次 |
最近记录: |