开发者

Regex for positive float numbers

For example:

10

0.1

1.2323开发者_开发技巧4

123.123

0.000001

1.000

.3

And wrong examples:

0001.2

-12

-1.01

+2.3

EDIT: standart JavaScript regex.


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.


I've stumbled on this page a few times, here is my solution for any one who stumbles here after me:

A regex like a=(\d+\.?\d* | \d*\.?\d+) matches all decimals numbers without a sign but includes things like 002.0

A regex to filter those things are b=[1-9\.]+.*

So one solution is to say it matches the criteria if a & b matches. Or equivalently (contrapositive), see if there is no match for !a | !b. Unfortunately, most languages don't have a complete regex package; the 'and' and negate functions of regular languages isn't present usually. Two simple regexes I've found in code looks a lot nicer and are more maintainable than one complex one (I say this in context to this question & similar situations)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜