Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex allow digits and a single dot

Tags:

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.

like image 628
MacMac Avatar asked Apr 06 '11 17:04

MacMac


People also ask

How do you specify a dot in regex?

\d\d[- /.] \d\d is a better solution. This regex allows a dash, space, dot and forward slash as date separators. Remember that the dot is not a metacharacter inside a character class, so we do not need to escape it with a backslash.

What does ?= * Mean in regex?

. means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it.

Can you use regex with numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

How do you escape a dot in regex?

(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \.


2 Answers

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.

like image 103
Håvard Avatar answered Oct 12 '22 11:10

Håvard


\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* 
like image 45
Ilya Kogan Avatar answered Oct 12 '22 12:10

Ilya Kogan