import re
regex = re.compile(r"<(a|h1)\b.*?</\1>(*SKIP)(*F)|<(img)[^>]*>(*SKIP)(*F)|(\b222.*?\b)", flags=re.DOTALL | re.IGNORECASE)
test_str = ("<p>111 222 333</p>\n"
"<li>111 222 333</li>\n"
"<h1>111 222 333</h1>\n"
"<h2>111 222 333</h2>\n"
"<strong>111 222 333</strong>\n"
"<p><strong>111 222 333</strong></p>\n"
"<p>111 <a href=\"\">222</a> 333</p>\n"
"<img src=\"image.png\" alt=\"222\">\n"
"<p>111 222 <img src=\"image.png\" alt=\"222\"> 333 222</p>")
subst = "<a href=\"#link\">\\2</a>"
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