ojhawkins
ojhawkins

Reputation: 3278

Decimal regex & Empty String

I have this javascript Regex (3 decimal places wiht a single dot)

^\d+(\.\d{1,3})?$

I want to also match on an empty string "" which i believe is

^$

How can I combine these into 1 regex

These should be the passing tests

"" //empty string
1
1.
1.0
1.00
1.000
123456789
0
.0
.00
.000

I hope I have covered all of them.

Upvotes: 1

Views: 2309

Answers (4)

Daniel Gimenez
Daniel Gimenez

Reputation: 20504

The digit period case was a difficult one, that my original answer missed. This answer is simpler than the others, covers all cases, and doesn't have any false matches.

  • Start of the string
  • Match Either
    • digits 1+ times then optional "."
    • "." as long as there is a digit ahead
  • digits 0-3 times
  • end of string

Expression

^((\d+\.?|\.(?=\d))?\d{0,3})$

REY

Upvotes: 1

Matt R. Wilson
Matt R. Wilson

Reputation: 7575

Not including the empty space, your current expression doesn't seem to pass your requirements.

^\d*\.?\d{0,3}$

Optional leading digits, optional point, up to three more digits before the end.

EDIT: @Guffa noticed that my original solution would also match simply a dot, "."

^\d*((\d\.)|(\.\d))?\d{0,3}$

This version replaces the \.? check with a check for a digit followed by a dot, or a dot followed by a digit, or neither.

Upvotes: 3

Guffa
Guffa

Reputation: 700342

Make an expression with three different cases:

  • zero or more digits
  • one or more digits, period, zero to three digits
  • zero or more digits, period, one to three digits

This will pass all your tests, and also the string "." will not pass:

^(\d*|\d+\.\d{0,3}|\d*\.\d{1,3})$

Demo: http://jsfiddle.net/Guffa/9pnwk/

Upvotes: 2

mucio
mucio

Reputation: 7119

I would rather go for a ==="" or your regex comparison, just for performance's sake

Upvotes: 1

Related Questions