import re
regex = re.compile(r"^(?![\W_])((?:([\w+-]{2,})\.?){1,})(?<![\W_])@(?![\W_])(?=[\w.-]{5,})(?=.+\..+)(?1)(?<![\W_])", flags=re.MULTILINE)
test_str = ("# 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.")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
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 Python, please visit: https://docs.python.org/3/library/re.html