import re
regex = re.compile(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
""", flags=re.IGNORECASE | re.MULTILINE | re.VERBOSE)
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 = 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