# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(<script\b[^><]*>)(.*?)(<\/script>)|\bon\w+\s*=\s*\K(?|(\")([^\"]+)\"|(')([^']+)')"
test_str = ("<div id='content' onClick='abc()'>Lorem On='abc' ipsum on to</div>\n"
"<input id='a' type='range'>\n"
"<input id='b' type='range'>\n"
"<script>abc();</script>\n\n\n\n"
"Jan23: The following is an addition set of tests including escaping quotes and .replace(/'/ situations that can cause problems.\n\n\n"
" <div id='content'\n"
" onClick='yyy(\"ere\\'xyz\\'\").value=\\'ewew\\'; yyy(\"jhrhej\")'\n"
" >Lorem On='abc' ipsum on to</div>\n\n\n"
" <input id='a' type='range'\n"
" onPress=\"xxx(document.getElementById(\\\"abc\\\"))\"\n"
" onSomething=\"yyy(\\'fehrje\\')\"\n"
" onSomethingElse=\"document.getElementById('content').innerHTML.replace(/\"/g, \\\"dq\\\")\">\n"
" <input id='b' type='range'>\n\n"
" <script>\n"
" function abc() {console.log('abc()');};\n"
" function xxx(elem) {console.log('xxx:'+elem.className);};\n"
" function yyy(str) {console.log('yyy:'+str);};\n\n"
" yyy(\"ere\\'xyz\\'\");\n"
" yyy(\"jhrhej\");\n\n"
" var aaa=document.getElementById('content').innerHTML;\n"
" var bbb=document.getElementById('content').innerHTML;\n"
" abc();\n"
" aaa.replace(/'/g, \"single-quotes\");\n"
" bbb.replace(/'/g, 'single-quotes');\n"
" aaa.replace(/\"/g, \"quotes\");\n"
" bbb.replace(/\"/g, 'quotes');\n"
" </script>\n\n"
"</body>\n"
"</html>")
matches = re.finditer(regex, test_str, re.IGNORECASE | re.DOTALL)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
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