# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"# Time:\s(?<timestamp>.*)\n#.*Id:\s(?<id>.*)\n#\sQuery_time:\s(?<duration>[\d.]*)\s.*time:\s(?<lock_time>[\d.]*)\s.*_sent:\s(?<returned>\d*)\s.*_examined:\s(?<searched>\d*)\n(?<sql>[\s\S]*)"
test_str = (" \n"
"# Time: 210607 16:27:16\n"
"# User@Host: doctime_db_usr[doctime_db_usr] @ [10.2.0.79] Id: 13021\n"
"# Query_time: 20.504504 Lock_time: 0.000233 Rows_sent: 52 Rows_examined: 13827347\n"
"SET timestamp=1623083236;\n"
"SELECT\n"
"substring( substring_index( uri, '/', -1 ) , 1, LENGTH(substring_index( uri, '/', -1 )) - 38 ) AS uri,\n"
"namespace,\n"
"method,\n"
"count(*) AS hits\n"
"FROM\n"
"user_hits\n"
"WHERE\n"
"namespace = 'hospitals' AND\n"
"controller = 'queue' AND\n"
"method = 'file'\n"
"GROUP BY\n"
"substring( substring_index( uri, '/', -1 ) , 1, LENGTH(substring_index( uri, '/', -1 )) - 38 )\n"
"UNION\n"
"SELECT\n"
"uri,\n"
"namespace,\n"
"method,\n"
"count(*) AS hits\n"
"FROM\n"
"user_hits\n"
"WHERE\n"
"uri LIKE '%export%'\n"
"GROUP BY\n"
"method\n"
"ORDER BY hits DESC;\n")
matches = re.finditer(regex, test_str, re.MULTILINE)
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