import re
regex = re.compile(r"^\w+(?:[_-][^\W_]+)*@(?![\d._-]+\.[^\W_]+$)[^\W_]+(?:[_-][^\W_]+)*\.[^\W_]{2,3}$", flags=re.MULTILINE)
test_str = ("xxx@_domain.com\n"
"xxx@domain_.com\n"
"xxx@-domain.com\n"
"xxx@domain-.com\n"
"-xxx@domain.in\n"
"xxx@111.com\n"
"xxx@1and1.com\n"
"xxx@us.com\n"
"xxx@my-india.com\n"
"xxx@me2.com\n"
"xxx@tv.com\n"
"xxx@abc_efg.com\n"
"_muth@tamil.com\n"
"xx-u@my-india.commmmm\n"
"x-xx@1and1.com\n\n"
"xxx@_domain.com => invalid @ starts with _\n"
"xxx@domain_.com => invalid domain ends with _ \n"
"xxx@-domain.com => invalid @ starts with - ( hypen)\n"
"xxx@domain-.com => invlaid domain ends with - (hypen)\n"
"-xxx@domain.in => invalid domain start with - (hypen)\n"
"xxx@111.com => invalid domain only contains numbers\n"
"xxx@1and1.com => valid domain contains both number and chars\n"
"xxx@us.com => valid\n"
"xxx@my-india.com => valid\n"
"xxx@me2.com => valid\n"
"xxx@tv.com =>\n"
"xxx@abc_efg.com => valid _ inside the chars\n"
"_muth@tamil.com => valid _ start with ")
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