'Iranian Grade Average Regex

I need a regex to handle the Iranian Grade average, regex should cover all these rules

  1. Range of number should be between 0 to 20.
  2. Numbers could be decimal except 20.
  3. Integer part and decimal part should include one or two numbers.
  4. If you use '.' you should have at least one decimal number.

examples:

20 true
19.99 true
14.5 true
12 true
4 true
0.22 true
00.02 true
10 true
14.23 true
09.23 true


21 false
30 false
123 false
12.222 false
09. false
4. false
.2 false
099 false
1.123 false



Solution 1:[1]

I tested this pattern and it works:

/(?<!\S)(([0-1]?[0-9])(.)([0-9]?[0-9])|([0-1][0-9])|\d{1}|(20))(?!\S)/

Solution 2:[2]

If it's to match a string with an Iranian Grade Average, then this regex pattern will match only the true ones.

^(?:[01]?[0-9]|20)(?:[.][0-9]{1,2})?$

^ : start of a line or string
(?:[01]?[0-9]|20) : number from 00 or 0 to 19, or 20
(?:[.][0-9]{1,2})? : optional 1 to 2 decimals
$ : end of line or string

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mehdi Nasiri
Solution 2 LukStorms