2

I need to do a regular expression to match the floats only, what i got is the following :

[\-\+]?[0-9]*(\.[0-9]+)?

But this match also the below 123123132 , 05/03/1994

I only need want to match the number with the decimal point

osos
  • 2,103
  • 5
  • 28
  • 42

3 Answers3

3

Your regex is almost correct for your purpose.

It finds 123123132, because the last part is optional. Removing the ? solves that.

[-+]?[0-9]*(\.[0-9]+)

With that adjustment, it might still find matches in strings like .12/39/3239, if you don't want that to happen, insert enforce matching over the complete string by inserting ^ and $:

^[-+]?[0-9]*(\.[0-9]+)$
L3viathan
  • 26,748
  • 2
  • 58
  • 81
1

How about:

([+-]?[0-9]*\.[0-9]*)

You can see it working here

karthik manchala
  • 13,492
  • 1
  • 31
  • 55
Matthew North
  • 553
  • 5
  • 20
1

Here is a regexp handling also existing exponents:

[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?

Regular expression visualization

Debuggex Demo

Additionally you should force the hole string to be matched to avoid matchings within your date values.

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

By the way here is a nice tutorial about matching floating point numbers using regular expressions: http://www.regular-expressions.info/floatingpoint.html.

wumpz
  • 8,257
  • 3
  • 30
  • 25