Last active
August 1, 2023 10:28
-
-
Save scanbix/35baa5448c8f9934c932989591b34ec8 to your computer and use it in GitHub Desktop.
regex decimal validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Reference: https://stackoverflow.com/questions/12117024/decimal-number-regular-expression-where-digit-after-decimal-is-optional | |
You need a regular expression like the following to do it properly: | |
/^[+-]?((\d+(\.\d*)?)|(\.\d+))$/ | |
The same expression with whitespace, using the extended modifier (as supported by Perl): | |
/^ [+-]? ( (\d+ (\.\d*)?) | (\.\d+) ) $/x | |
or with comments: | |
/^ # Beginning of string | |
[+-]? # Optional plus or minus character | |
( # Followed by either: | |
( # Start of first option | |
\d+ # One or more digits | |
(\.\d*)? # Optionally followed by: one decimal point and zero or more digits | |
) # End of first option | |
| # or | |
(\.\d+) # One decimal point followed by one or more digits | |
) # End of grouping of the OR options | |
$ # End of string (i.e. no extra characters remaining) | |
/x # Extended modifier (allows whitespace & comments in regular expression) | |
For example, it will match: | |
123 | |
23.45 | |
34. | |
.45 | |
-123 | |
-273.15 | |
-42. | |
-.45 | |
+516 | |
+9.8 | |
+2. | |
+.5 | |
And will reject these non-numbers: | |
. (single decimal point) | |
-. (negative decimal point) | |
+. (plus decimal point) | |
(empty string) | |
The simpler solutions can incorrectly reject valid numbers or match these non-numbers. | |
============================== | |
find non-breaking space \x{A0} | |
find brackets with any numbers \([0-9]+\) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment