Regex help

Folks,

I want to allow a string hat either contains a space or not. e.g. “1234AB” or “1234 AB”.

my current regex only allows a string with a space, but not when it has no space.


var input   = "1234 AB";
var string = input.match(/^[1-9]\\d{3}\\s[A-Z]{2}$/)[0];
document.write(string);

Actually I got this working by specifying a \s{0,1}.

The trouble with using \s{0,1} is that it will be okay with a space or no space, but if a dash is used, such as in 1234-AB it will fail to work.

Using [ \-] instead of \s is a more robust solution, if there might be any risk of a dash be used as a separator instead.

\s{0,1} is the same as \s?

? = {0,1}

  • = {0,}
  • = {1,}

No, \s{1} is the same as \s

What I was saying earlier is that \s is less capable of picking up formatting variations that he mentioned in a related thread

Given a string such as “1234-abc” or “1234 abc” or “1234abc”

So for the “1234-abc” to be successful, you cannot use \s for that, and must instead use something else such as [ \-]

Which means that what used to be \s{0,1} would now be [ \-]{0,1}
which I would preferably use as [ \-]? where the question mark indicates that it’s optional.