Reputation: 34
I have this regex range
/([a-zA-Z0-9\.\-#_~!$&'()*+,;=:]+)/
for the allowable characters for a user's username. I would like to add the @ char to the range but limit its quantity to 0 or 1 and have it's location be irrelevant.
I know @{0,1} is the quantifier syntax, but how do I combine it with my range to meet my specifications.
Requirements:
Thanks
Upvotes: 2
Views: 169
Reputation: 1166
Just copy your regex and add the @
in the middle:
/^([-a-zA-Z0-9.#_~!$&'*+,;=:()]+@?[-a-zA-Z0-9.#_~!$&'*+,;=:()]+)$/
or more precisely:
/^(@|@?[-a-zA-Z0-9.#_~!$&'*+,;=:()]+|[-a-zA-Z0-9.#_~!$&'*+,;=:()]+@|[-a-zA-Z0-9.#_~!$&'*+,;=:()]+@[-a-zA-Z0-9.#_~!$&'*+,;=:()]+)$/
Upvotes: -1
Reputation: 2121
i would like to make you Regex small by using \w in it
here is what w indicates in regex
please look ahead for this,this will reduce length of your regex.
^(?!(?:[^@\n]*@){2})[\w.#_~!$&'()*+,;=:@]+$
Upvotes: 0
Reputation: 785156
You can use a lookahead regex like this:
/^(?!(?:[^@]*@){2})[-a-zA-Z0-9.#_~!$&'()*+,;=:@]+$/
(?!(?:[^@]*@){2})
will disallow 2 @
in your input thus allowing you to use 0 or 1 @
in input. Also check demo.
Upvotes: 3