简体   繁体   中英

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

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+)%?$";

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)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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