Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for Decimal or Blank

Tags:

regex

Sorry for the potentially dumb question but I am trying to pull together a regular expression that will allow:

A number with 1 or 2 numbers before a decimal point, and 0-6 numbers after the decimal point. However I also need to allow the field to be blank if so required.

Valid Examples

0.952321
1.20394
12.12
25
Blank

Invalid Examples

123.45678
1.1234567

Please can anyone help?

like image 740
Phil P Avatar asked Mar 24 '10 14:03

Phil P


2 Answers

^(?:\d{1,2}(?:\.\d{0,6})?)?$

Should do the trick.

\d     matches any digit
{n,m} specifies the number of occurrences
(?: ) creates an anonymous group
^     specifies the start of the string
$               the end of the string
?     means the group is optional
like image 151
AxelEckenberger Avatar answered Oct 08 '22 18:10

AxelEckenberger


^(?:|\d{1,2}(?:\.\d{0,6})?)$

The part before the pipe matches blank. The part after matches one or two digits optionally followed by a period and up to six digits. The ?: are so we don't use capturing groups unless needed.

Hope this helps!

like image 41
miorel Avatar answered Oct 08 '22 18:10

miorel