^(?:\+1[a-zA-Z0-9]+|(?!\+1).*[a-zA-Z0-9]+.*)?$
Explanation:
The regular expression is split into two cases: ( CASE1 | CASE2 )
First case: \+1[a-zA-Z0-9]+
matches any text that starts with +1
followed by one or more alphanumeric characters ([a-zA-Z0-9]+
represents selecting one or more characters that are either from a to z, from A to Z, or from 0 to 9)
Second case: (?!\+1).*[a-zA-Z0-9]+.*
matches any text that does NOT start with +1
((?!\+1)
), and is followed by any number of characters as long as it contains at least one alphanumeric character (.*[a-zA-Z0-9]+.*
means choose zero or more of any character, then the alphanumeric regex stated earlier, and finally zero or more characters again)
These two cases correspondingly fulfill your criteria #3 and #2.
The rule #1 is handled by the ?
at the end of the entire expression, indicating that all of it is optional, thus allowing for an empty string.
Please take note of the following:
(?:something)
is utilized to match a string without capturing it.
(?!something)
ensures that a particular string is not matched
\
is employed to escape special characters like +
when you want them to be treated as ordinary characters
+
signifies one or more instances of the preceding item
*
denotes zero or more instances of the preceding item
I hope this explanation was helpful!