最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin8浏览0评论

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.

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.

Share Improve this question edited Nov 19, 2011 at 0:24 Felix Kling 817k180 gold badges1.1k silver badges1.2k bronze badges asked Nov 19, 2011 at 0:22 zaqzaq 2,6613 gold badges32 silver badges39 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 8

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)

Some options:

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

Try this regex:

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

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.

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";
发布评论

评论列表(0)

  1. 暂无评论