zaq
zaq

Reputation: 2661

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.

Upvotes: 6

Views: 4606

Answers (5)

gilly3
gilly3

Reputation: 91497

If you only care about the start of the string, don't bother with a regular expression that searches to the end:

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

Or you can do it without using a regular expression:

myString.substr(0,1) != "+" || myString.substr(0,2) == "+1";

Upvotes: 0

ruakh
ruakh

Reputation: 183270

Some options:

^($|\+1|[^+])        <-- cleanest
^(\+1.*|[^+].*)?$    <-- clearest
^(?!\+(?!1))         <-- coolest :-)

Upvotes: 6

Nick Knowlson
Nick Knowlson

Reputation: 7426

This should work: ^(\+1.*|[^+].*)?$

It is straightforward, too.

\+1.* - Either match +1 (and optionally some other stuff)
[^+].* - Or one character that is not a plus (and optionally some other stuff)
^()?$ - Or if neither of those two match, then it should be an empty string.

Upvotes: 1

mVChr
mVChr

Reputation: 50177

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)

Upvotes: 8

deviousdodo
deviousdodo

Reputation: 9172

Try this regex:

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

Upvotes: 1

Related Questions