import re
regex = re.compile(r"^(\p{L}+)(?:_\p{L}+)*_(\p{L})\p{L}*$", flags=re.MULTILINE)
test_str = ("Thomas_J_Perkins\n\n"
"Jennifer_Scanner\n\n"
"Amanda_K_Loso\n\n"
"Aaron_Cole\n\n"
"Mark_L_Lamb")
subst = "\\1_\\2"
result = regex.sub(subst, test_str)
if result:
print(result)
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