简体   繁体   English

正则表达式以验证百分比

[英]Regular expression to validate percentage

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 但问题是如果输入像5%5%那么它就是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 UPDATE

string expression = @"^(\d+|\d+[.]\d+)%?$";

You get partial matches, because your expression does not anchor both sides. 您获得部分匹配,因为您的表达式不会锚定双方。 Your regex anchors the beginning, but not the end of the match. 你的正则表达式锚定了开始,但不是匹配的结束。

Moreover, the placement of the left anchor ^ is incorrect, because it applies only to the left sub-expression 而且,左锚点^的放置是不正确的,因为它仅适用于左子表达式

Adding a $ at the end should help: 在最后添加$应该有助于:

^(\d|\d%)$

However, this is suboptimal: since the prefix of both expressions is the same, and they differ by an optional suffix % , you could use %? 但是,这不是最理想的:因为两个表达式的前缀相同,并且它们的可选后缀% ,您可以使用%? to simplify the expression: 简化表达式:

^\d+%?$

This is better, but it would not match decimal point. 这样更好,但它不会与小数点匹配。 To add this capability, change the expression as follows: 要添加此功能,请按如下所示更改表达式:

^(\d+|\d*[.]\d+)%?$

You're expression is the following: match when you find either of the following: a single digit at the start of the input string, or a single digit anywhere, followed by %. 您的表达式如下:当您找到以下任一项时匹配:输入字符串开头的单个数字,或任何地方的单个数字,后跟%。 Probably not what you intended. 可能不是你想要的。 I'd try something like this: 我会尝试这样的事情:

var expression = @"^\d+(\.\d+)?%?$";

This would translate to: match a positive number of digits at the start of the string, optionally followed by a dot and any number of digits (fractional part), optionally ending with a % sign. 这将转换为:匹配字符串开头的正数位数,可选地后跟一个点和任意数量的数字(小数部分),可选地以%符号结尾。

You could try this ^\\d+([.]\\d+)?%?$ it works with: (tested) 你可以尝试这个^\\d+([.]\\d+)?%?$它适用于:(已测试)

1000.55
1000.65%
100
100%
1400%
5.5
5.5%

Hope it helps! 希望能帮助到你!

i think this is the best one : 我认为这是最好的一个:

^\d{0,2}(\.\d{1,4})? *%?$

source : Here 来源: 这里

this worked for me: 这对我有用:

/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{0,2})?)$/

For only two decimals and no more than 100 [0.00 - 100.00] 只有两位小数且不超过100 [0.00 - 100.00]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM