Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for decimal numbers

Tags:

regex

decimal

Could anybody provide a regular expression for a number that has to be between 1 and 17 in length, and could optionally contain a mantissa of up to 4 places? The length of 17 includes both the characteristic and the mantissa.

Edit:

The length of 17 excludes the decimal point.

Valid examples:

12345678901234567 
1234567890123.4567 
123456789012345.67
12.34

Invalid:

12345678901234.5678 (Length of numerals = 18)

Thanks.

like image 509
aliensurfer Avatar asked Mar 03 '10 06:03

aliensurfer


2 Answers

^\d{17}$|^\d{13}(?=.{5}$)\d*\.\d*\d$

Regex explained:

^\d{17}$    //A string of 17 digits 
|           //or
^\d{13}     //13 digits followed by
(?=.{5}$)   //5 characters, of which 
\d*\.\d*    //one is a decimal point and others are digits
\d$         //and the last one is a digit
like image 145
Amarghosh Avatar answered Sep 22 '22 20:09

Amarghosh


OK, this is the best I could do:

/^\d{1,17}$|(?=^.{1,18}$)^\d+\.\d{1,4}$/

Basically, match 1-17 digits, or strings of length 1-18 which consist of two sets of digits separated by a period. The right set can only contain between 1-4 digits.

like image 39
polygenelubricants Avatar answered Sep 21 '22 20:09

polygenelubricants