简体   繁体   中英

Regex in c# for digit with comma

I would like to use a RegEx in order to verify that an input is

empty -> to 100

exemple : 0 or 1 or 10,1 or 20.2 or 99

Only positive values, 0 or null value to 100, and accepting dot and comma. Anyone could give me the right C# regex please ?

Thanks a lot :)

Try this (if there is a comma or a period, at least one following digit is required):

^\d*(?:(?:\.|\,)\d+)?$

A great tool for these requests: http://regexpal.com/

Regards

Lots of samples for numeric regex's can be found here

Regex Lib

Regex is about matching characters. It doesn't understand about numbers.

Try parsing it instead using double.TryParse() , and if that fails because the string has , as instead of . , replace , with . and then try again.

Try this:

(100|\d{1,2}[.,]\d+)

But it's more correct to use Double.Parse() here.

string str = '10,1';
bool valid = false;
double num = -1;

str = str.Replace(",", ".");

if (String.IsNullOrEmpty(str)) {
    valid = true;
} else {
    try {
        num = Double.Parse(str);
    } catch (Exception ex) {
        valid = false;
    }

    if (num >= 0 && num <= 100) {
        valid = true;
    }
}

*Why didn't I use Double.TryParse() instead?

Sadly, failure to parse will make the outcome 0 , which falls to the valid condition.

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