Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Matching numbers with floating point

Tags:

regex

I have this pattern:

[0-9]*\.?[0-9]

It matches numbers but it also matches 3.5.4 as:

  1. 3.5
  2. .4

How to fix that(this input shouldn't be matched)?
UPDATE:
this also should work on input: 1 3.5.4 10

1.2. is not allowed
.3 is allowed

any char that is not poart of numer is not allowed, like: a1 2.4f 3. 45, 67!

like image 459
ronik Avatar asked Jan 26 '10 13:01

ronik


2 Answers

To match a json number:

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

JSON number

Use this regex to match .123:

^[-]?((0|[1-9][0-9]*)(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?$
like image 181
kev Avatar answered Oct 17 '22 07:10

kev


Updated answer after comment from poster:

Use lookahead / lookbehind to make sure that the characters before and after are spaces:

Here's a version that closely matches yours, but that won't make partial matches:

(?:^|(?<=\s))[0-9]*\.?[0-9](?=\s|$)

For both these examples, when run on the string 1 2.3.4 5.6 it matches only 1 and 5.6.

like image 23
Mark Byers Avatar answered Oct 17 '22 06:10

Mark Byers