import re
regex = re.compile(r"(<(p|li)\b[^<>]*>[^<>\n]*)\b(Cat|Dog|Fish)\b([^<>\n]*<\/\2>)", flags=re.MULTILINE)
test_str = ("(1) <p> Cat test dfdsf</p>\n"
"(2) <p> Cat.</p>\n"
"(3) <p>Cat.</p>\n"
"(4) <p class=\"test\">Cat</p>\n"
"(5) <li>Cat</li>\n"
"(6) <p>Catfgdggh</p>\n"
"(7) <div>Cat</div>")
subst = "$1lol$4"
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