I’m trying to match an email address here is what I’ve come up with so far :
String text = "gandalf_storm@mymail.com";
String regex = "(\\w+)@{1}(\\w+){2,}\\.{1}\\w{2,4}";
This however works with following cases :
gandalf_storm@mymail.com
gandalfstorm@mymail.com
gandalf2storm@mymail.com
So it matches any alphanumeric character repeated once or more that comes before one @ followed by any alphanumeric character repeated at least two times(which is minimal characters for any domain name) followed by one .(dot) and followed by any alphanumeric character repeated at least 2 times and at most 4 times(because there are domains such as .us or .mobi).
This expression however does not work with emails such as :
gandalf.storm@mymail.com
gandalf.storm@mydomain.me.uk
gandalf.storm@mysubdomain.mydomain.me.uk
gandalf.storm@mysubdomain.mysubdomain.mydomain.me.uk
etc as many subdomains
or
gandalf.storm@mymail.com
gandalf2storm@mydomain.me.uk
gandalf_storm@mysubdomain.mydomain.me.uk
gandalfstorm@mysubdomain.mysubdomain.mydomain.me.uk
I’ve just started to learn regex and I found interesting to try to solve problems such as these by using regex .. not partially but for each case, any help would be much appriciated. Thank you
This question has been asked many, many times before here on SO. Here’s why you don’t want to use regexes
to parse email addresses. Note please that that monster of a regex doesn’t even handle comments.