Sachin Chaudhari
Sachin Chaudhari

Reputation: 113

Regex for digits and space as thousand separator

This regex should allow me to input numbers with space as thousand separator, but some how it is accepting alphabets and special characters too. Can someone help me with what is wrong with the regex:

reg = new RegExp("^(?:\s*([0-9]* [0-9]{3})\s*)*$||[0-9]*");

Upvotes: 3

Views: 2884

Answers (2)

Dreamer
Dreamer

Reputation: 86

The grouping of OR seems incorrect (also, use |, not ||).

Try this

   new RegExp(
    "^("  //start of line
    + "(?:" // number with thousands separator
      + "[0-9]{1,3}" //1..3 digits once 
      + "(?: [0-9]{3})*?" //exactly 3 digits, preceded by space, any number of times
    + ")"
    + "|(?:" // or just number 
      + "[0-9]+" //any number of digits without spaces
    + ")"
    + ")$");

Depending or your needs, you can allow or reject non-three digit parts.

Upvotes: 2

Riaan Nel
Riaan Nel

Reputation: 2535

I think that you can greatly simplify that regex.

^[0-9 ]+$

This matches numbers with or without spaces as a separator. However, note that it will match on a space anywhere (not only as a thousands separator). It should be easy enough to tweak though.

Edit: Here's another alternative that forces spaces to separate thousands in the number.

^[0-9]{1,3}()\s?([0-9]{3}\s?)+$

Upvotes: 0

Related Questions