Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression - Match any string not starting with + but allow +1

I need a regular expression for JavaScript that will match any string that does not start with the + character. With one exception, strings starting with +1 are okay. The empty string should also match.

For example:

"" = true
"abc" = true
"+1" = true
"+1abc" = true
"+2" = false
"+abc" = false

So far I have found that ^(\+1|[^+]?)$ takes care of the +1 part but I cannot seem to get it to allow more characters after without invalidating the first part. I thought that ^(\+1|[^+]?).*?$ would work but it seems to match everything.

like image 377
zaq Avatar asked Nov 19 '11 00:11

zaq


1 Answers

First, the second part of your matching group isn't optional, so you should remove the ?.

Second, since you only care about what shows up at the beginning, there's no need to test the whole string until the $.

Lastly, to make the empty string return true you need to test for /^$/ as well.

Which turns out to:

/^(\+1|[^+]|$)/

For example:

/^(\+1|[^+]|$)/.test("");      // true
/^(\+1|[^+]|$)/.test("abc");   // true
/^(\+1|[^+]|$)/.test("+1");    // true
/^(\+1|[^+]|$)/.test("+1abc"); // true
/^(\+1|[^+]|$)/.test("+2");    // false
/^(\+1|[^+]|$)/.test("+abc");  // false

See demo

(console should be open)

like image 200
mVChr Avatar answered Nov 09 '22 21:11

mVChr