Tyler Drake
Tyler Drake

Reputation: 34

How do I insert a regex quantifier into a range

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:

  1. A - Z alphabet
  2. 0 - 9 numerals
  3. Only 1 @ allowed
  4. Special Characters: # - _ ~ ! $ & ' ( ) * + , ; = :

Thanks

Upvotes: 2

Views: 169

Answers (3)

CaHa
CaHa

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

Himesh Aadeshara
Himesh Aadeshara

Reputation: 2121

i would like to make you Regex small by using \w in it

here is what w indicates in regex

  • \w : Matches any word character (alphanumeric & underscore). Only matches low-ascii characters (no accented or non-roman characters). Equivalent to [A-Za-z0-9_]

please look ahead for this,this will reduce length of your regex.

^(?!(?:[^@\n]*@){2})[\w.#_~!$&'()*+,;=:@]+$

Upvotes: 0

anubhava
anubhava

Reputation: 785156

You can use a lookahead regex like this:

/^(?!(?:[^@]*@){2})[-a-zA-Z0-9.#_~!$&'()*+,;=:@]+$/

RegEx Demo

(?!(?:[^@]*@){2}) will disallow 2 @ in your input thus allowing you to use 0 or 1 @ in input. Also check demo.

Upvotes: 3

Related Questions