Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for finding decimal/float numbers?

i need a regular expression for decimal/float numbers like 12 12.2 1236.32 123.333 and +12.00 or -12.00 or ...123.123... for using in javascript and jQuery. Thank you.

like image 427
MBehtemam Avatar asked Apr 21 '12 03:04

MBehtemam


People also ask

How do you find decimals in regular expressions?

A regular expression for a decimal number needs to checks for one or more numeric characters (0-9) at the start of the string, followed by an optional period, and then followed by zero or more numeric characters (0-9). This should all be followed by an optional plus or minus sign.

What is the expression to represent floating point number?

[0-9]+|[0-9]+). This regular expression matches an optional sign, that is either followed by zero or more digits followed by a dot and one or more digits (a floating point number with optional integer part), or that is followed by one or more digits (an integer).

How do I extract a float number from a string in Python?

To extract a floating number from a string with Python, we call the re. findall method. import re d = re. findall("\d+\.


2 Answers

The right expression should be as followed:

[+-]?([0-9]*[.])?[0-9]+ 

this apply for:

+1 +1. +.1 +0.1 1 1. .1 0.1 

Here is Python example:

import re #print if found print(bool(re.search(r'[+-]?([0-9]*[.])?[0-9]+', '1.0'))) #print result print(re.search(r'[+-]?([0-9]*[.])?[0-9]+', '1.0').group(0)) 

Output:

True 1.0 

If you are using mac, you can test on command line:

python -c "import re; print(bool(re.search(r'[+-]?([0-9]*[.])?[0-9]+', '1.0')))"  python -c "import re; print(re.search(r'[+-]?([0-9]*[.])?[0-9]+', '1.0').group(0))" 
like image 44
lbsweek Avatar answered Oct 08 '22 05:10

lbsweek


Optionally match a + or - at the beginning, followed by one or more decimal digits, optional followed by a decimal point and one or more decimal digits util the end of the string:

/^[+-]?\d+(\.\d+)?$/ 

RegexPal

like image 164
Paul Avatar answered Oct 08 '22 03:10

Paul