# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"""
(?(DEFINE)
(?<quote>['"])
(?<pair>
(?>
\w+
|(?:
(?<pairQuote>(?"e))[^'"]+?\k<pairQuote>
)
)
\s*\:
)
(?<string>
(?<stringQuote>(?"e))[\S\s]*?(?<!\\)\k<stringQuote>
)
(?<integer>\-?\d+(?:\.\d+)?(?:e[-+]\d+)?)
(?<scalar>true|false|null|(?&integer))
(?<elements>
\s*(?&value)
(?(R&array)|(?>(?:\s*\,(?&elements))|\s*))
)
(?<array>\[(?>(?&elements)|\s*)\])
(?<value>
(?&object)
|(?&string)
|(?&scalar)
|(?&array)
)
(?<members>
\s*(?&pair)\s*(?&value)
(?(R&object)|(?>(?:\s*\,(?&members))|\s*))
)
(?<object>\{(?&members)?\})
)
\A(?&object)\Z
"""
test_str = ("{\"menu\": {\n"
" \"header\": \"SVG Viewer\",\n"
" \"items\": [\n"
" {\"id\": \"Open\"},\n"
" {\"id\": \"OpenNew\", \"label\": \"Open New\"},\n"
" null,\n"
" {\"id\": \"ZoomIn\", \"label\": \"Zoom In\"},\n"
" {\"id\": \"ZoomOut\", \"label\": \"Zoom Out\"},\n"
" {\"id\": \"OriginalView\", \"label\": \"Original View\"},\n"
" null,\n"
" {\"id\": \"Quality\"},\n"
" {\"id\": \"Pause\"},\n"
" {\"id\": \"Mute\"},\n"
" null,\n"
" {\"id\": \"Find\", \"label\": \"Find...\"},\n"
" {\"id\": \"FindAgain\", \"label\": \"Find Again\"},\n"
" {\"id\": \"Copy\"},\n"
" {\"id\": \"CopyAgain\", \"label\": \"Copy Again\"},\n"
" {\"id\": \"CopySVG\", \"label\": \"Copy SVG\"},\n"
" {\"id\": \"ViewSVG\", \"label\": \"View SVG\"},\n"
" {\"id\": \"ViewSource\", \"label\": \"View Source\"},\n"
" {\"id\": \"SaveAs\", \"label\": \"Save As\"},\n"
" null,\n"
" {\"id\": \"Help\"},\n"
" {\"id\": \"About\", \"label\": \"About Adobe CVG Viewer...\"}\n"
" ],\n"
" \"test\": [\n"
" \"Some value\",\n"
" 4,\n"
" null,{}\n"
" ],\n"
" \"empty_array\":[-0.34E+4]\n"
"}}")
matches = re.finditer(regex, test_str, re.IGNORECASE | re.MULTILINE | re.VERBOSE)
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