javaregexapostrophe

In Java Regex - email validation, How to allow apostrophe before @ and not as first and last character before @ and not two consecutive apostrophe?


Regex Used:

EMAIL_VALID_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+"[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";

Now i need to allow apostrophe before @ and also it should not allow apostrophe as first and last character and also two consecutive apostrophe before @.

Can someone modify the above regex to handle the mentioned scenarios and can you explain it?

Valid emails: test@gmail.com, test's@gmail.com, t@gmail [Even if single character is passed before, it is valid] Invalid emails: 'test@gmail.com, test'@gmail.com, 'test'@gmail.com, test''s@gmail.com


Solution

  • You can replace (\\.[_A-Za-z0-9-]+)*@ with ([.'’][_A-Za-z0-9-]+)*@:

    ^[_A-Za-z0-9+-]+(?:[.'’][_A-Za-z0-9-]+)*@[_A-Za-z0-9-]+(?:\.[_A-Za-z0-9-]+)*\.[A-Za-z]{2,}$
    

    Define in Java with

    EMAIL_VALID_REGEX = "^[_A-Za-z0-9+-]+(?:[.'’][_A-Za-z0-9-]+)*@[_A-Za-z0-9-]+(?:\\.[_A-Za-z0-9-]+)*\\.[A-Za-z]{2,}$"
    

    See the regex demo

    The [.'’] part is a character class matching ., ' or .

    The ^[_A-Za-z0-9+-]+(?:[.'’][_A-Za-z0-9-]+)*@ part now matches

    If there is a comma, or apostrophe, they will be allowed only in between the chars matched with the [_A-Za-z0-9-] character class, as both occurrences of [_A-Za-z0-9-] patterns on both ends of [.'’] is quantified with + (i.e. they require at least one char to match).

    To apply the same restriction to -, _ and +, use

    EMAIL_VALID_REGEX = "^[A-Za-z0-9]+(?:[+_.'’-][A-Za-z0-9]+)*@[_A-Za-z0-9-]+(?:\\.[_A-Za-z0-9-]+)*\\.[A-Za-z]{2,}$"
    

    See this regex demo.