Regular expression to match decimal places with or without leading zeros

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

I don't know the correct expression well. Above regex is not allowed to enter .2. But it allows all other decimal numbers like 0.2, 0.02, etc. I need to do this expression so that a number like .2, .06, etc.

+2


source to share


5 answers


Just change +

after [0]

to an asterisk `* ':

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

      



So instead of allowing one or more zeros preceding point, just allow 0 or more.

+9


source


I love this regex for floating point numbers, its pretty smart as it doesn't match 0.0

as a number. This requires at least one non-zero number on either side of the period. I realized that I would have broken it into pieces in order to understand it more deeply.

^             #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 regex has two small patterns in it, the first matches cases where a number> = 1 (having at least one non-zero character to the left of.), Optionally allowing a period with one or more finite 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 a solution to the problem [0]*

.

A couple of regexp shortcuts, you can replace any instance [0-9]

with \d

in most regexp variants. Also [0]

matches only 0

, so you can just use 0*

instead [0]*

. Last regex:

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

      

+8


source


I would use this:

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

      

This allows numeric expressions starting with

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

Allowed:

123
123.
123.45
.12345

      

But not:

.
01234

      

+2


source


You can also use a simple expression like:

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

      

+1


source


Replace it:

^([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*)$

      

0


source







All Articles