正则表达式验证百分比 [英] Regular expression to validate percentage
本文介绍了正则表达式验证百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想验证输入字符串,这样
5.0是正确的
5.5%是正确的
于是我开始用下面的代码:
字符串decimalstring1 =10000.55;
串decimalstring2 =5%5%;
字符串表达式= @^ \d | \d%;
正则表达式objNotNumberPattern =新的正则表达式(表达);
Console.WriteLine(objNotNumberPattern.IsMatch(decimalstring1));
Console.WriteLine(objNotNumberPattern.IsMatch(decimalstring2));
到Console.ReadLine();
但问题是,像5%5%输入它给正确
我如何修改这个表达式来完成这项工作?
解决方案
的String []输入=新的String [] {
1000.55,
1000.65%,
100
100%,
1400%,
5.5,
5.5%,
×,
%
};
字符串表达式= @[]?^ \d + \d *%$;
正则表达式objNotNumberPattern =新的正则表达式(表达);
的foreach(在输入VAR项)
Console.WriteLine(objNotNumberPattern.IsMatch(项目));
更新
字符串表达式= @^(\d + | \d + \d +。])%$?;
I want to validate input string such that
5.0 is correct
5.5% is correct
So I started with the following code:
string decimalstring1 = "10000.55";
string decimalstring2 = "5%5%";
string expression = @"^\d|\d%";
Regex objNotNumberPattern = new Regex(expression);
Console.WriteLine(objNotNumberPattern.IsMatch(decimalstring1));
Console.WriteLine(objNotNumberPattern.IsMatch(decimalstring2));
Console.ReadLine();
But the problem is that with input like 5%5% it gives correct
How can I modify this expression to make this work?
解决方案
string[] inputs = new string[] {
"1000.55",
"1000.65%",
"100",
"100%",
"1400%",
"5.5",
"5.5%",
"x",
".%"
};
string expression = @"^\d+[.]?\d*%?$";
Regex objNotNumberPattern = new Regex(expression);
foreach (var item in inputs)
Console.WriteLine(objNotNumberPattern.IsMatch(item));
UPDATE
string expression = @"^(\d+|\d+[.]\d+)%?$";
这篇关于正则表达式验证百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文