tags:

views:

116

answers:

4

Hi,

  ^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]+\.[0-9]*[1-9][0-9]*)$

I don't know regular expression well. Above regular expression does not allow input .2 .but it allows all other decimals like 0.2 , 0.02 etc . I need to make this expression allow the number like .2 ,.06 , etc.....

+6  A: 

Just change the + after [0] into an ansterisk `*":

^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]*\.[0-9]*[1-9][0-9]*)$

So instead of allowing one or more zeroes preceding the dot, just allow 0 or more.

Joey
just planned to post :)^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]*\.[0-9]*[1-9][0-9]*)$
Viktor Jevdokimov
+4  A: 

I like this regexp for floating point numbers, its pretty smart in that it wont match 0.0 as a number. It requires at least one non-zero number on either side of the period. Figured I'd break it into its parts to provide a deeper understanding of it.

^             #Match at start of string
 (            #start capture group
  [0-9]*       # 0-9, zero or more times
  [1-9]        # 1-9
  [0-9]*       # 0-9, zero or more times
  (            #start capture group
   \.           # literal .
   [0-9]+       # 0-9, one or more times
  )?           #end group - make it optional
 |            #OR - If the first option didn't match, try alternate
  [0]+         # 0, one or more times ( change this to 0* for zero or more times )
  \.           # literal .
  [0-9]*       # 0-9, zero or more times
  [1-9]        # 1-9
  [0-9]*       # 0-9, zero or more times
 )            #end capture group
$             #match end of string

The regexp has two smaller patterns inside of it, the first matches cases where the number is >= 1 (having at least one non-zero character left of the .) optionally allowing for a period with one or more trailing numbers. The second matches <1.0 and ensures that there is at least one non-zero digit on the right side of the dot.

Johannes' answer already gives you the [0]* solution to the problem.

Couple of regexp shortcuts, you could replace any instance of [0-9] with \d in most regexp flavors. Also [0] only matches 0 so you might as well just use 0* instead of [0]*. The final regexp:

/^(\d*[1-9]\d*(\.\d+)?|0*\.\d*[1-9]\d*)$/
gnarf
Nice explanation. Just as a side remark: to prevent leading zeros, delete the first [0-9]*
Martijn
A: 

I would use this:

^(?:(?:0|[1-9][0-9]*)(?:\.[0-9]*)?|\.[0-9]+)$

This allows number expressions starting with either

  • some digits, followed by optional fractional digits, or
  • just fractional digits.

Allowed:

123
123.
123.45
.12345

But not:

.
01234
Gumbo
The original regexp supplied wouldn't allow anything that equaled 0 either... Yours lost that
gnarf
A: 

Replace it with:

^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]*\.[0-9]*[1-9][0-9]*)$

or even shorter:

^(\d*[1-9]\d*(\.\d+)?|[0]*\.\d*[1-9]\d*)$
Veton