Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to validate percentage

Tags:

c#

regex

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?

like image 782
AMH Avatar asked Feb 12 '23 13:02

AMH


1 Answers

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+)%?$";
like image 113
MJVC Avatar answered Feb 15 '23 09:02

MJVC