Regular expression to find the number, 0 or decimal
I'm looking for a regular expression which whill validate the number starting from 0 up - and might include decimals.
An开发者_JS百科y idea?
A simple regex to validate a number:
^\d+(\.\d+)?$
This should work for a number with optional leading zeros, with an optional single dot and more digits.
^...$
- match from start to end of the string (will not validateab12.4c
)\d+
- At least one digit.(...)?
- optional group of...\.\d+
- literal dot and one or more digits.
Because decimal numbers may or may not have a decimal point in them, and may or may not have digits before that decimal point if they have some afterwards, and may or may not have digits following that decimal point if they have some before it, you must use this:
^(\d+(\.\d*)?|\d*\.\d+)$
which is usually better written:
^(?:\d+(?:\.\d*)?|\d*\.\d+)$
and much better written:
(?x)
^ # anchor to start of string
(?: # EITHER
\d+ (?: \. \d* )? # some digits, then optionally a decimal point following by optional digits
| # OR ELSE
\d* \. \d+ # optional digits followed then a decimal point and more digits
) # END ALTERNATIVES
$ # anchor to end of string
If your regex compiler doesn’t support \d
, or also depending on how Unicode-aware your regex engine is if you should prefer to match only ASCII digits instead of anything with the Unicode Decimal_Number
property (shortcut Nd
) — that is, anything with the Numeric_Type=Decimal
property — then you might wish to swap in [0-9]
for all instances above where I’ve used \d
.
I always use RegExr to build my regular expressions. It is sort of drag-and-drop and has a live-preview of your regex and the result.
It'll look something like ^0[,.0-9]*
^[0-9]+(\.[0-9]+)?$
Note that with this expression 0.1 will be valid but .1 won't.
This should do what you want:
^[0-9]+([,.][0-9]+)?$
It will match any number starting with 0 and then any number, maybe a , or . and any number
'/^([0-9\.]+)$/'
will match if the test string is a positive decimal number
精彩评论