import re
regex = re.compile(r"(<span class='customer)(' id='phone[^>]*>)([^<]+)")
test_str = ("GIVEN:\n"
"<div>\n"
" <span class='customer' id='phone$0'>Home</span>\n"
"<br/>\n"
" <span class='customer' id='phone$1'>Business</span>\n"
"<br/>\n"
" <span class='customer' id='phone$2'>Mobile</span>\n"
"</div>\n\n"
"DESIRED:\n"
"<span class='customer NewClass' id='phone$1'>Organization</span>\n")
subst = "$1 NewClass$2Organization"
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