import re
regex = re.compile(r"(<a\s+href=\"http:(?!\/\/(?:www\.)?example\.com)[^\"]*\")>", flags=re.IGNORECASE | re.DOTALL)
test_str = ("<a href=\"/somepage.htm\">1</a>\n"
"<a href=\"http://www.somesiteexternal.com/\">2</a>\n"
"<a href=\"http://www.example.com/somepage.htm\">3</a>\n")
subst = "\\1 target=\"_blank\">"
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