How to include dot once as last character in regex?

Viewed 166

I'm trying to make regex in JavaScript that matches numbers between 1-100 and includes two decimals. Example numbers that need to be included in the regex:

1 1.1 1.15 0.5 100 100.00

Example numbers that need to be excluded:

101 100.01 100.1 55.999

This is my regex at the moment:

^(?:100(?:\.00?)?|\d?\d(?:\.\d\d?)?)$

This works otherwise but I also need to include two numbers followed by a decimal or 100 followed by a decimal like this:

14. 9. 100.

This is because I'm running the regex check each time a button is pressed in an input field and even though number like 0.5 is allowed by the current regex, I can't type it in because 0. is not allowed.

4 Answers

You will need to use two separate regexps here, one for the live input validation (just what you described in the question, that will let you input allowed values), and another one for a final "on-submit" validation (that will check the validity of the whole input string). Otherwise, you won't be able to input 0.5 like values.

The regex for live input validation is:

/^(?:100(?:\.0?0?)?|\d\d?(?:\.\d?\d?)?)$/

See this regex demo. Note how the ? quantifiers make patterns optional, especially the \d and 0 after \. patterns.

The regex for final validation of numbers starting with 0.01 to 100 is

/^(?!0*(?:\.0*)?$)(?:100(?:\.00?)?|\d?\d?(?:\.\d\d?)?)$/

See this regex demo.

Make the numbers after the dot optional, too.

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

If you want to disallow 0 before the dot if the numbers after are all zero or nothing, probably include a separate negative lookahead for that:

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

Nothing here or in your original regex should disallow 0.5; perhaps add more debugging details if that is genuinely something you are grappling with.

You may use this regex for your task:

^(?:0?\.(?:\d?[1-9]|[1-9]\d)|[1-9]\d?(?:\.\d{1,2})?|100(?:\.0{1,2})?)$

RegEx Demo

With your shown samples, could you please try following.

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

Online demo for above regex

Explanation: Adding detailed explanation for above.

^                      ##Matching from starting of value here.
(?:                    ##Starting 1st capturing group here.
  100(?:\.0{1,2})?|    ##matching 100 with or without 1 to 2 zeroes OR
  (?:                  ##Starting 2nd capturing group here.
     (?:\d\d?)         ##In a non-capturing group matching 0 to 9 and 0 to 9 optional.
     (?:\.\d{1,2})?    ##In a non-capturing group matching dot followed by 1 or 2 digits
  )                    ##Closing 2nd capturing group here.
)$                     ##Closing 1st capturing group at the end of value.
Related