简体   繁体   中英

Javascript regex positive negative decimal number

I need a regex that would match a positive and negative decimal value, empty string ('') and also minus only ('-'). Since I need it inside the function that handles the change of a numeric field and in order to add a negative value the user firstly adds the "-" or deletes the old value (""), I need to match all these 3 conditions.

So, to sum up, the regex should allow:

  • positive & negative decimal values (also 0)
  • "" (empty string)
  • "-" (minus string)

What I have until now is:

function sanitizeInputValue(value: string) {
  var re = new RegExp('^$|^-?\\d{1,9}(\\.\\d{1,2})?$');
  return value.match(re) === null ? 0 : value;
}

Use javascript's built in Number to convert the string into a numeric value right before you return from the function.

Also, I modified your regex so that it can accept input like .23 and 0.2345 .

 function sanitizeInputValue(value) { var re = new RegExp('^$|^-?(\\d+)?(\\.?\\d*)?$'); return value.match(re) === null? 0: Number(value); } console.log(sanitizeInputValue("-23")); // -23 console.log(sanitizeInputValue("42.123")); // 42.123 console.log(sanitizeInputValue("-.34")); // -0.34 console.log(sanitizeInputValue("")); // 0 console.log(sanitizeInputValue("-8.")); // -8 console.log(sanitizeInputValue("-8.4")); // -8.4

You can make matching the digits with decimal parts optional so you would also match the hyphen only ^$|^-?(?:\d{1,9}(\.\d{1,2})?)?$

As then all parts are optional, you can omit the ^$ and then all parts are optional.

^-?(?:\d{1,9}(?:\.\d{1,2})?)?$

Explanation

  • ^ Start of string
  • -? Optional hyphen
  • (?: Non capture group
    • \d{1,9} match 1-9 times a digit
    • (?:\.\d{1,2})? Optionally match a dot and 1-2 digits
  • )? Close non capture group and make it optional as well
  • $ End of string.

Regex demo

 var re = new RegExp("^-?(?:\\d{1,9}(?:\\.\\d{1,2})?)?$"); [ "", "-", "1", "1.2", "test", "1234567890", "1.123", "-2", "-2.6" ].forEach(s => console.log(s + " --> " + re.test(s)));

Edit

As you also want to match -8. and don't want to limit the amount of digits, you could use:

^-?(?:\d+\.?\d*)?$

Explanation

  • ^ Start of string
  • -? Optional -
  • (?: Non capture group
    • \d+\.?\d* Match 1+ digits, optional dot and 0+ digits
  • )? Close group and make it optional
  • $ End of string

Regex demo

 var re = new RegExp("^-?(?:\\d+\\.?\\d*)?$"); [ "-8.", "", "-", "1", "1.2", "test", "1234567890", "1.123", "-2", "-2.6" ].forEach(s => console.log(s + " --> " + re.test(s)) );

function sanitizeInputValue(value) {
  var re = /^$|\-?[0-9]\d*(\.\d*)?|-/;
  return value.match(re) ? value : 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM