Decimal point regular expression

I am trying to check a regular expression text box ...

regex expression=(\d{0,4})?([\.]{1})?(\d{0,2}) 

I have a decimal point problem. decimal point is optional. regex should only check for one decimal point.

  example 1.00 ,23.22 , .65 is valid 1.. or 23.. is invalid. 

Any suggestions for improving my regex?

+4
source share
2 answers

Try the following: ^\d{1,4}(\.\d{1,2})?$

It must comply with:

 1 200 9999 12.35 522.4 

But not:

 1000000 65. .65 10.326 65..12 

Edit:

If you want to match 65. or 9999. use this instead (see comments):

 ^\d{1,4}(\.(\d{1,2})?)?$ 
+4
source

Use application logic instead

Although you could, of course, create a regular expression for this, it seems easier to check the data type or class, or just look at your input for decimals, and then count them. For example, using Ruby:

  • Make sure this value is equal to pay or integer.

     # Literal value is a float, so it belongs to the Float class. value = 1.00 value.class == Fixnum or value.class == Float => true # Literal value is an integer, so it belongs to the Fixnum class. value = 23 value.class == Fixnum or value.class == Float => true 
  • Count the decimal numbers and make sure there is no more than one.

     # Literal value is a float. When cast as a string and scanned, # only one decimal should be found. value = 23.22 value.to_s.scan(/\./).count <= 1 => true # The only way this could be an invalid integer or float is if it a string. # If you're accepting strings in the first place, just cast all input as a # string and count the decimals it contains. value = '1.2.3' value.to_s.scan(/\./).count <= 1 => false 
0
source

All Articles