简体   繁体   English

正则表达式 - 匹配任何不以+开头但允许+1的字符串

[英]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. 我需要一个JavaScript的正则表达式,它将匹配任何不以+字符开头的字符串。 With one exception, strings starting with +1 are okay. 除了一个例外,以+1开头的字符串是可以的。 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. 到目前为止,我发现^(\\+1|[^+]?)$负责+1部分,但我似乎无法在不使第一部分无效的情况下允许更多字符。 I thought that ^(\\+1|[^+]?).*?$ would work but it seems to match everything. 我以为^(\\+1|[^+]?).*?$会起作用,但它似乎匹配所有东西。

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. 最后,要使空字符串返回true,您还需要测试/ ^ $ /。

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 :-)

This should work: ^(\\+1.*|[^+].*)?$ 这应该工作: ^(\\+1.*|[^+].*)?$

It is straightforward, too. 它也很简单。

\\+1.* - Either match +1 (and optionally some other stuff) \\+1.* - 匹配+1(以及可选的其他一些东西)
[^+].* - 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. ^()?$ - 或者如果这两者都不匹配,那么它应该是一个空字符串。

试试这个正则表达式:

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

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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM