admin管理员组

文章数量:1313001

I'm trying to write a regular expression to match both positive and negative floating points of any length of characters. I tried this

/^-|[0-9\ ]+$/

However this is still wrong because for example it would match "46.0" and "-46.0" but will also match "4-6.0" which I don't want.

At the moment i'm using this

/^-|[0-9][0-9\ ]+$/

This fixes the first problem but this will match something like "-4g" and that is also incorrect.

What expression can I use to match negative and positive floating points?

I'm trying to write a regular expression to match both positive and negative floating points of any length of characters. I tried this

/^-|[0-9\ ]+$/

However this is still wrong because for example it would match "46.0" and "-46.0" but will also match "4-6.0" which I don't want.

At the moment i'm using this

/^-|[0-9][0-9\ ]+$/

This fixes the first problem but this will match something like "-4g" and that is also incorrect.

What expression can I use to match negative and positive floating points?

Share Improve this question asked Nov 6, 2011 at 3:27 ZeenoZeeno 2,72111 gold badges38 silver badges61 bronze badges 3
  • 1 I'm skeptical SO would have been faster than a search. – Dave Newton Commented Nov 6, 2011 at 3:37
  • possible duplicate of How to detect a floating point number using a regular expression – Dave Newton Commented Nov 6, 2011 at 3:40
  • This es up first searching for "regex for negative float" – user2105469 Commented Mar 12, 2014 at 18:36
Add a ment  | 

4 Answers 4

Reset to default 7

Why not the following?

parseFloat(x) === x

If you really want a regex, there are entire pages on the internet dedicated to this task. Their conclusion:

/^[-+]?[0-9]*\.?[0-9]+$/

or

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

if you want to allow exponential notation.

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

This also allows for an exponent part. If you don't want that, just use

/^[-+]?[0-9]+(?:\.[0-9]+)?$/

Hope this helps.

Well mine is bit lesser, optional you can remove {1,3} limits to minimum 1 and max 3 numbers part and replace that with + to make no limit on numbers.

/^[\-]?\d{1,3}\.\d$/

Try this...

I am sure, it's work in javascript.

var pattern = new RegExp("^-?[0-9.]*$");

if (pattern.test(valueToValidate)) {

   return true;

} else {

 return false;

}

本文标签: regexJavascript Regular expression to allow negative and positive floating point numbersStack Overflow