Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to validate decimal numbers

Tags:

c#

.net

regex

The regular expression should match below criteria. The number of elements before and after the dot can be any. Only 1 dot is allowed and negative sign is allowed at first position only. I do not require comma.

Example:

1
-1
-1.
1.
1.2
-.2
-0.2
000.300

All above expressions should result true.

So if i break up..

  1. An optional negative sign at first place.
  2. Zero or more digit before dot.
  3. Dot is optional. Can occur max one time. It can be pure integer number also.
  4. O or more digits after dot.

Any help will be appreciated.

like image 930
Jason Avatar asked Mar 21 '23 23:03

Jason


2 Answers

What you probably want is this:

^-?\d*\.?\d*

Which will give you a possible negative sign (-?),
followed by any number of digits (\d*),
followed by a possible decimal point (\.),
followed by any number of trailing digits after the decimal point (\d*).

Since you just want to validate whether it's a valid float or not, @MarcinJuraszek has a good point, you may not want to be using regex here.

like image 60
eric Avatar answered Apr 02 '23 03:04

eric


1) An optional negative sign at first place:

^ : Start of string

- : The minus

? : Makes the preceeding character optional

2) Zero or more digits

/d : digit

* : match as many (including zero) of the previous thing

3) Optional dot

. : the dot

? : makes the dot optional

4) 0 or more details after dot

/d : digit

* : match as many (including zero) of the previous thing

So all together: ^-?/d*.?/d*

like image 42
hankd Avatar answered Apr 02 '23 03:04

hankd