Reputation: 25
i need a regex to accept both integers or float but not any other characters like for int ex: 28128 and float with two decimal precision ex: 123123.00 or 123213.05 ...
i have for integers and float [separately] like below
var numbers_only = /^[0-9]+$/;
var decimal_only = /^[0-9]+\.[0-9]+$/;
so how can i merge this into one...so i can accept integers and float(2 decimal places)...
Upvotes: 2
Views: 53
Reputation: 9430
You can always merge multiple patterns using |
(OR) operator:
/^([0-9]+|[0-9]+\.[0-9]+)$/
Upvotes: 0
Reputation: 174706
Use an optional group.
^\d+(?:\.\d+)?$
(?:\.\d+)?
will match the decimal part if there is any in the input string. ?
after the non-capturing group makes that group as optional.
For two decimal places.
^\d+(?:\.\d{2})?$
Upvotes: 3