user4773404
user4773404

Reputation: 25

regex to search numbers or float numbers in one pattern

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

Answers (2)

n-dru
n-dru

Reputation: 9430

You can always merge multiple patterns using | (OR) operator:

/^([0-9]+|[0-9]+\.[0-9]+)$/

Upvotes: 0

Avinash Raj
Avinash Raj

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})?$

DEMO

Upvotes: 3

Related Questions