-5

This regex for email

"(\\s*[\\w\\.-]+@([\\w\\-]+\\.)+((co|gov).(in|uk)|com|gov|org|edu|in)\\s*)|" +
             "(\\s*(http\\://|www\\.|http\\://www\\.)?([\\w\\-]+\\.)+((co|gov)\\.(in|uk)|com|gov|org|edu|in)(( / )\\S*)*(\\s|$))"

can any one tell me the simplest regex? how can I write it in short form it is very complecated.

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Nilesh
  • 19
  • 1

2 Answers2

3

Don't use a regex for this. Java has what it takes to check the validity of an email address in javax.mail:

    try {
        new InternetAddress(theInput, true);
    } catch (AddressException e) {
        // handle exception
    }

Find the jar here.

fge
  • 119,121
  • 33
  • 254
  • 329
  • InternetAddress is predefined class or we need to create it? – Nilesh Jun 17 '13 at 06:43
  • See edit, I have posted a link to a place where you can get the jar – fge Jun 17 '13 at 06:46
  • Aftercpattern matching i want to perform below operation on address. What should i do for that? what that class return? Matcher m = pattern.matcher(input); while (m.find()) { String base = m.group(); String strtrget = base.trim(); strtrget=strtrget.replaceAll("\\.","-@@@-"); strtrget=strtrget.replaceAll(" ", "-"); HashmapHypen.put(base, strtrget.replace("[-]+", "-")); input = input.replaceAll(base, " "+strtrget+" "); – Nilesh Jun 17 '13 at 06:57
  • before Matcher : try { input=input.replaceAll("http\\: / / ","http\\://"); String expression = "(\\s*[\\w\\.-]+@([\\w\\-]+\\.)+((co|gov).(in|uk)|com|gov|org|edu|in)\\s*)|" + "(\\s*(http\\://|www\\.|http\\://www\\.)?([\\w\\-]+\\.)+((co|gov)\\.(in|uk)|com|gov|org|edu|in)(( / )\\S*)*(\\s|$))"; // Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE); Pattern pattern = Pattern.compile(expression); – Nilesh Jun 17 '13 at 07:00
  • `InternetAddress` checks that the email is valid, that's all. What operations do you need to do after that? First of all you should get `InternetAddress` to work; only then consider operations. One step at a atime. – fge Jun 17 '13 at 07:04
0

Simpler is what fge has mentioned in his answer but if due to any reason you want to use regex, here is the one for email address validation:

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

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136