Home > Software engineering >  Regex to not allow particular special characters at start or end of email name in email address
Regex to not allow particular special characters at start or end of email name in email address

Time:06-24

I have the following regex condition for email address.

var value = /^[a-zA-Z0-9._-] @[a-zA-Z0-9] \.[a-zA-Z{2,}$/

But I dont want the name to start or end with period(.) or underscore(_) or hyphen (-) and this given special characters should include in middle only.

for eg :

            [email protected] Invalid
             [email protected] Invalid
              [email protected] Invalid
              [email protected] Invalid
              [email protected] Invalid
              [email protected] Invalid
              [email protected] Invalid
              [email protected] Invalid
              [email protected] Valid
              [email protected] Valid
              [email protected] Valid

I am trying to figure out the solution and learn in the process.

CodePudding user response:

You can use

var value = /^[a-zA-Z0-9] (?:[._-][a-zA-Z0-9] )*@[a-zA-Z0-9] \.[a-zA-Z]{2,}$/

Details:

  • ^ - start of string
  • [a-zA-Z0-9] - one or more letters/digits
  • (?:[._-][a-zA-Z0-9] )* - zero or more occurrences of ./_/- and then one or more letters/digits
  • @ - a @ char
  • [a-zA-Z0-9] - one or more letters/digits
  • \. - a dot
  • [a-zA-Z]{2,} - two or more letters
  • $ - end of string.

See the regex demo.

  • Related