Regular expression - match any string that does not start with +, but allows +1

I need a regular expression for JavaScript that matches any string that doesn't start with a + . With one exception, lines starting with +1 are fine. An empty string should also match.

For instance:

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

So far, I have found that ^(\+1|[^+]?)$ Will take care of the +1 part, but I cannot get it to allow more characters after the first part is invalid. I thought ^(\+1|[^+]?).*?$ Would work, but that seems to be all.

+6
source share
5 answers

First, the second part of your comparable group is optional, so should you delete ?.

Secondly, since you only care about what appears at the beginning, there is no need to check the entire line up to $.

Finally, to return the empty string true, you also need to check for / ^ $ /.

What turns out:

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

For instance:

 /^(\+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)

+8
source

Some options:

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

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

It is also simple.

\+1.* - or a +1 match (and maybe some other things)
[^+].* - Or one character that is not a plus (and possibly some other material)
^()?$ - or if none of these two matches, then this should be an empty string.

+1
source

Try this regex:

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

If you only care about the beginning of the line, don't worry about the regular expression that searches until the end:

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

Or you can do this without using a regex:

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

Source: https://habr.com/ru/post/901868/


All Articles