Search code examples
regexemail-validation

Regular Expression for email formatting without hypen at first and last


I have created the regular expression which will take the email address as in following format:

abc@xyz.com.in

Regular Expression

/^(?!-)[\w-\.]+@([\w-]+\.)+[\w-]{2,4}/

I am trying to do the email which is not having hyphen at start and last.

Invalid Format

-abc@xyz.com
abc@xyz.com-

valid format

abc@xyz.com
abc@xyz.com.in

Solution

  • Add \w to each end of your regex, and include the end anchor$

    ^\w[\w.-]+@([\w-]+\.)+[\w-]{2,4}\w$
    

    Note also the dot doesn't need escaping within a character class.