import re
regex = re.compile(r"^/(media/catalog/product/cache)/\d+/thumbnail/(\d+x\d+)/[a-z0-9]+/(\S+)", flags=re.MULTILINE)
test_str = ("/media/catalog/product/cache/1/thumbnail/543x403/db978388cfd007780066eaab38556cef/l/e/legal_slide01.jpg\n"
"# check if match with above:\n"
"/pub/media/catalog/product/cache/543x403/l/e/legal_slide01.jpg\n\n"
"/media/catalog/product/cache/1/thumbnail/543x403/db978388cfd007780066eaab38556cef/n/u/number1.png\n"
"# check if match with above:\n"
"/pub/media/catalog/product/cache/543x403/n/u/number1.png")
subst = "/pub/$1/$2/$3"
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