Regex for positive float numbers

Try this here

^(?:[1-9]\d*|0)?(?:\.\d+)?$

See it here online on Regexr

If matching the empty string is not wanted, then you can add a length check to your regex like

^(?=.+)(?:[1-9]\d*|0)?(?:\.\d+)?$

The positive lookahead (?=.+) ensures that there is at least 1 character


This will pass all your test cases, multi-line mode enabled:

/^(?!0\d)\d*(\.\d+)?$/mg

Explanation:

/^              # start of regex and match start of line
(?!0\d)         # not any number with leading zeros
\d*             # consume and match optional digits
(\.\d+)?        # followed by a decimal and some digits after, optional.
$               # match end of line
/mg             # end of regex, match multi-line, global match

RegExr: http://regexr.com?2tpd0


Consider the regular expression:

^[0-9]*(?:\.[0-9]*)?$

This regular expression will matches floating point number like:

 - .343
 - 0.0
 - 1.2
 - 44
 - 44.
 - 445.55
 - 56.
 - . //Only dot(.) also matches
 - empty string also matches

The above regular expression will will not accept:

- h32.55 //Since ^ is used. So, the match must start at the beginning
   of the string or line.
- 23.64h //Since $ is used. So, the match must occur at the end of the string or before \n at the end of the line or string.

Consider the regular expression:

^[0-9]+(?:\.[0-9]+)?$

This regular expression will matches floating point number like:

 - 45
 - 45.5
 - 0.0
 - 1.2
 - 445.55

This regular expression will not accept:

 - h32.55 //Since ^ is used. So, the match must start at the beginning
   of the string or line. 
 - 23.64h //Since $ is used. So, the match must occur at the end of the string or before \n at the end of the line or string.
 - 44. 
 - . //Only dot(.) does not matches here
 - empty string also does not matches here

Pure floating point:

^(([0-9]+(?:\.[0-9]+)?)|([0-9]*(?:\.[0-9]+)?))$ 
  • You can check the regular expression here.
  • Refer MSDN page for additional information.