import re
regex = re.compile(r"^(?=.{1,39}$)^[a-zA-Z\d]+(?:-[a-zA-Z\d]+)*$", flags=re.MULTILINE)
test_str = ("-username\n"
"_username_\n"
"__us_ername\n"
"us_er\n"
"username-\n"
"1user--name\n"
"132uname-\n"
"-uname1234\n"
"-username-\n"
"user--name\n"
"av34axc-\n"
"1234567890A1234567890B1234567890C1234567890D\n\n"
"Username\n"
"a-a\n"
"aBc\n"
"BaC\n"
"1-1\n"
"1-2-3-4\n"
"q-1-2-3\n"
"q-q-q-q-q\n"
"username\n"
"123username123\n"
"username3123\n"
"1234\n"
"user-name\n"
"13-13\n"
"q1-q2-q3\n"
"a\n"
"A\n"
"1234567890A1234567890B1234567890C123456\n"
"1234567890A123456-7890B1234567890C12345")
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