import re
regex = re.compile(r"(\b(?'first_word'[A-Z](?!([A-Z0-9]*\b|[[:alnum:]]*_)(?# the word isn't in all caps and doesn't contain underscores))(?:[a-z0-9]*)))|(\G(?'trailing_word'[A-Z][a-z0-9]*))", flags=re.MULTILINE)
test_str = ("PascalCase\n"
"Pascal \n"
"PascalCaseCase\n"
"Pascal684Case\n"
"Pas45calCase\n"
"PascalCase6523Case\n"
"PascalCaseCaseCase\n"
"PPascal\n"
"PascalCCase\n"
"camelCase\n"
"// some random commentary with Capitalized and SCREAMING letters\n"
"SCREAMING_SNAKE_CASE\n"
"Pascal_Snake_Case\n")
subst = "\\L${first_word}${trailing_word:+_\\L${trailing_word}:}"
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