import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?=^[\\w.@!#$%&'*+/=?^`\\{|\\}~-]{7,254}$)(?<username>(?=^[\\w.!#$%&'*+/=?^`\\{|\\}~-]{1,64}@)[\\w!#$%&'*+/=?^`\\{|\\}~-]+(?:\\.[\\w!#$%&'*+/=?^`\\{|\\}~-]+)*)@(?<domain>(?=\\b[a-z\\d.-]{5,252}$)(?:[a-z\\d](?:[a-z\\d-]{0,61}[a-z\\d])\\.)+(?:(?:[a-z](?:[a-z-]{0,61}[a-z]))|(?:(?=[a-z\\d-]*?[a-z])(?=[a-z\\d-]*?[\\d])[a-z\\d](?:[a-z\\d-]{0,61}[a-z\\d]))))$";
final String string = "Add the multiline (/m) Regex option for testing or go to te Unit Tests section...\n\n"
+ "Valid addresses:\n\n"
+ "test@email.com\n"
+ "Test2@email.com\n"
+ "another.test@email.com\n"
+ "testwith+flag@email.com\n"
+ "withanyofthese#!%$'&+*-/=?^_.{|}~symbols@email.com\n"
+ "upto64charactersusername56789c123456789d123456789e123456789f1234@email.com\n"
+ "test@with.any.number.of.labels.separated.by.dots.email.com\n"
+ "test@even.with.digits.1234567890.email.com\n"
+ "test@and-hypens-email.com\n"
+ "t@upto252charactersdomainname89c123456789d123456789e123456789f123.butonlyupto63charactersperlabel6789j123456789k123456789l1234567.9m123456789n123456789o123456789p123456789q123456789r123456789s1.3456789t123456789u123456789v123456789w123456789x12.email.com\n\n"
+ "Invalid adresses:\n\n"
+ ".usernamestartingwithdot@email.com\n"
+ "usernameendingwithdot.@email.com\n"
+ "havingtwo..consecutivedotsintheusername@email.com\n"
+ "test@orinthedomainname..email.com\n"
+ "test@having.all.numerical.top-level-domain.888\n"
+ "havinglessthan2characterperlabel@1.a.email.com\n"
+ "(havingothersymbolsnotlisted)@email.com\n"
+ "usingotherthanletters.digits.and-hyphens{anddots}inthedomainname@[123.45.67.89]\n";
final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
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