import re
regex = re.compile(r"<span.*?(?:itemprop\s*=\s*\"\s*name\s*\"\s*)?class\s*=\s*\"\s*itemprop\s*\"\s*(?:itemprop\s*=\s*\"\s*name\s*\"\s*)?>(.*?)<\/span>", flags=re.DOTALL)
test_str = (" <div class=\"txt-block\" itemprop=\"contractors\" itemscope\n"
" itemtype=\"home\"> \n"
" <h4 class=\"inline\">Employs:</h4> <a href=\"/.../\" itemprop='url'><span class=\"itemprop\"\n"
" itemprop=\"name\">Carp 1</span></a>, <a href=\"/.../\"\n"
" itemprop='url'><span class=\"itemprop\" itemprop=\"name\">Carp\n"
" 2</span></a>, <a href=\"/.../\" itemprop='url'><span class=\"itemprop\"\n"
" itemprop=\"name\">Carp 3</span></a> <span\n"
" class=\"tots\">|</span>\n"
" <span class=\"see-more inline\"> <a href=\"/.../\" itemprop='url'>See full options</a> \n"
" </span>\n"
" </div>")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
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