简体   繁体   中英

Regex to allow numeric values between[1-100] and a percentage symbol

I want a regex to allow numeric values between 1 to 100 and one percentage symbol

Valid samples: 0%, 100%, 100, 0, 65%

Invalid samples: 101, 101%, 100.1, 65.6%, 65.6

Any help is appreciated

i dont speak regex but you saied any help would be appreciated so here i go:

    bool Verify(string input)
    {
        input = input.Replace("%", "");  // if it contains % remove it
        int value;
        if (Int32.TryParse(input, out value))   //if the input can be converted into a number
        {
            if (value > 1 && value < 100)  //and the value is in range
            {
                return true;  //return true to confirm it
            }
        }
        return false;  //in any other case return false
    }

Try this:

^(0*100{1,1}\.?((?<=\.)0*)?%$)|(^0*[1-9]\d{0,1}\.?((?<=\.)\d*)?%)$

It will allow 65% and 100% and discard 65 and 100.1%

Matches a percentage between 0 and 100 (inclusive). Accepts up to 2 decimal places. ex: 0% , 100% , .17%

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

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