Search code examples
javascriptregexregex-groupregex-greedy

regex for allowing alphanumeric, special characters and not ending with @ or _ or


I am new to regex , I created below regex which allows alpha numeric and 3 special characters @._ but string should not end with @ or . or *

^[a-zA-Z0-9._@]*[^_][^.][^@]$

it validates abc@ but fails for abc.


Solution

  • Your pattern allows at least 3 characters, where the last 3 are negated character classes matching any char other than the listed.

    The pattern ^[a-zA-Z0-9._@]*[^_][^.][^@]$ will match 3 newlines, and adding all the chars to a single character class ^[a-zA-Z0-9._@]*[^@._]$ will also match a single newline only.


    If you want to allow all 3 "special" characters and match at least 3 characters in total you can repeat the character class 2 or more times using {2,} and match a single char at the end without the special characters.

    ^[a-zA-Z0-9._@]{2,}[a-zA-Z0-9]$
    

    Regex demo

    Matching as least a single char (and not end with . _ @)

    ^[a-zA-Z0-9._@]*[a-zA-Z0-9]$
    

    Regex demo