Regex matching numbers and decimals
Here's a much simpler solution that doesn't use any look-aheads or look-behinds:
^\d*\.?\d+$
To clearly understand why this works, read it from right to left:
- At least one digit is required at the end.
7
works77
works.77
works0.77
works0.
doesn't work
empty string doesn't work - A single period preceding the digit is optional.
.77
works77
works..77
doesn't work - Any number of digits preceding the (optional) period.
.77
works0.77
works0077.77
works0077
works
Not using look-aheads and look-behinds has the added benefit of not having to worry about RegEx-based DOS attacks.
HTH
This is a fairly common task. The simplest way I know of to deal with it is this:
^[+-]?(\d*\.)?\d+$
There are also other complications, such as whether you want to allow leading zeroes or commas or things like that. This can be as complicated as you want it to be. For example, if you want to allow the 1,234,567.89 format, you can go with this:
^[+-]?(\d*|\d{1,3}(,\d{3})*)(\.\d+)?\b$
That \b
there is a word break, but I'm using it as a sneaky way to require at least one numeral at the end of the string. This way, an empty string or a single +
won't match.
However, be advised that regexes are not the ideal way to parse numeric strings. All modern programming languages I know of have fast, simple, built-in methods for doing that.
Nobody seems to be accounting for negative numbers. Also, some are creating a capture group which is unnecessary. This is the most thorough solution IMO.
^[+-]?(?:\d*\.)?\d+$