'RegEx for email with only one special character

I am trying to modify a regex for emails (gmail) that should contains special characters like _%+-. but only one, not more

I made 2 test cases below that are both passing

I also tried [a-z0-9]+.+[a-z0-9] instead of [A-Z0-9_%+-.] but both test cases are passing

enter image description here



Solution 1:[1]

I managed to find the right regex for my question

/^[A-Z0-9]+(?:[_%+.-][A-Z0-9]+)?@[A-Z0-9.-]+\.[A-Z]{2,4}$/i

Solution 2:[2]

As mentioned in the comments, you can try with

/^[A-Z0-9]+(?:[_%+.-][A-Z0-9]+)?@[A-Z0-9.-]+\.[A-Z]{2,4}$/i

or

/^[A-Z0-9]+[_%+.-][A-Z0-9]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i

(if there must be at least three chars before @ with . in the middle only). Try to give us more test cases to check your requirements, you can check here.

Solution 3:[3]

Try using this regex:

^[^@_\%+\-\.]+[^@][^@_\%+\-\.]+@[A-Za-z\.]+$

Explanation:

  • ^: begin of string
  • [^@_\%+\-\.]+: any character other than @ or special character (_%+-.)
  • [^@]: any character other than @ (here will match the special character, if present)
  • [^@_\%+\-\.]+: any character other than @ or special character (_%+-.)
  • @: @
  • [A-Za-z\.]+: any combination of alphabetical character and dot
  • $: end of string

Try it here.

Note: the considered special characters are the one you listed in your problem statement. If there are further special characters, you just need to add them inside explained part 2 and 4.

Solution 4:[4]

This should meet your need (some may be invalid in format): ^[a-z0-9]*[_%+\-.][a-z0-9]*...

If there must be characters surrounding those special chars (valid in format): ^[a-z0-9]+[_%+\-.][a-z0-9]+...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2004
Solution 2 rikyeah
Solution 3 lemon
Solution 4