import re
regex = re.compile(r"(\S[^\S\n]*\n)[^\S\n]*\n(?![^\S\n]*\n)")
test_str = ("\n\n"
"<nav>\n"
" \n"
" <ul>\n\n"
" <li><a href=\"#\">London</a></li>\n\n"
" <li><a href=\"#\">Paris</a></li>\n\n"
" <li><a href=\"#\">Tokyo</a></li>\n\n"
" </ul>\n\n"
"</nav>\n\n\n\n"
"<div>new context</div>\n\n\n\n"
"<div>new context</div>")
subst = "$1"
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