import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?![\\W_])((?:([\\w+-]{2,})\\.?){1,})(?<![\\W_])@(?![\\W_])(?=[\\w.-]{5,})(?=.+\\..+)(?1)(?<![\\W_])";
final String string = "# Valid\n"
+ "test@gm.com\n"
+ "test@gmail.com\n"
+ "aa-test@gmail.com\n"
+ "aa_test@gmail.com\n"
+ "aa.test@gmail.com\n"
+ "aa1test@gmail.com\n"
+ "aa1.test@gmail.com\n"
+ "aa1-test@gmail.com\n"
+ "1test@gmail.com\n"
+ "test@gmail.co.in\n"
+ "aa-test@gmail.co.in\n"
+ "aa_test@gmail.co.in\n"
+ "aa.test@gmail.co.in\n"
+ "aa1test@gmail.co.in\n"
+ "aa1.test@gmail.co.in\n"
+ "aa1-test@gmail.co.in\n"
+ "1test@gmail.co.in\n"
+ "addres+3@gmail.com\n"
+ "address1@gmail.com;adresse2@gmail.com;\n"
+ "address1@gmail.com;adresse2@gmail.com;address1@gmail.com;adresse2@gmail.com;\n"
+ "address1@gmail.com;\n"
+ "address1@gmail;adress2@gmail.com;addres+3@gmail.com; \n\n\n"
+ "# Invalid \n"
+ "test@gmail\n"
+ ".test@gmail.com\n"
+ "-test@gmail.com\n"
+ "_test@gmail.com\n"
+ "tes.t@gmail.com\n"
+ "t.e.st@gmail.com\n"
+ "t.-.est@gmail.com\n"
+ ".test.@gmail.com\n"
+ "test.@gmail.com\n"
+ "test.@.gmail.com\n"
+ "test@.gmail.com\n"
+ "test@.gmail.com.\n"
+ "test@gmail.com.";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html