MacMac
MacMac

Reputation: 35311

Regex allow digits and a single dot

What would be the regex to allow digits and a dot? Regarding this \D only allows digits, but it doesn't allow a dot, I need it to allow digits and one dot this is refer as a float value I need to be valid when doing a keyup function in jQuery, but all I need is the regex that only allows what I need it to allow.

This will be in the native of JavaScript replace function to remove non-digits and other symbols (except a dot).

Cheers.

Upvotes: 28

Views: 139193

Answers (5)

Sumit Kumar
Sumit Kumar

Reputation: 823

Try the following expression

/^\d{0,2}(\.\d{1,2})?$/.test()

Upvotes: 0

Roman Losev
Roman Losev

Reputation: 1941

My try is combined solution.

string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;

First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.

Second line cleans numbers after dot.

Upvotes: 3

Narasimha
Narasimha

Reputation: 105

Try this

boxValue = boxValue.replace(/[^0-9\.]/g,"");

This Regular Expression will allow only digits and dots in the value of text box.

Upvotes: 7

escargot agile
escargot agile

Reputation: 22379

\d*\.\d*

Explanation:

\d* - any number of digits

\. - a dot

\d* - more digits.

This will match 123.456, .123, 123., but not 123

If you want the dot to be optional, in most languages (don't know about jquery) you can use

\d*\.?\d*

Upvotes: 27

Håvard
Håvard

Reputation: 10080

If you want to allow 1 and 1.2:

(?<=^| )\d+(\.\d+)?(?=$| )

If you want to allow 1, 1.2 and .1:

(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )

If you want to only allow 1.2 (only floats):

(?<=^| )\d+\.\d+(?=$| )

\d allows digits (while \D allows anything but digits).

(?<=^| ) checks that the number is preceded by either a space or the beginning of the string. (?=$| ) makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.

Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.

Upvotes: 55

Related Questions