# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"""
# begin capture group 1
\{\s+"name":[ ]" # match '{' then 1+ whitespace chars, then '"name": "
(\w+) # match 1+ word chars, save to capture group 1
- # match '-'
(\w+) # match 1+ word chars, save to capture group 2
- # match '-'
(\w+) # match 1+ word chars, save to capture group 3
- # match '-'
(\w+) # match 1+ word chars, save to capture group 4
( # begin capture group 5
",\s+"units":[ ] # match '",', then 1+ whitespaces then '"units": '
"\w+" # match 1+ word chars
,\s+"value":[ ] # match ',', then 1+ whitespaces then '"value": '
\d+ # match 1+ digits
\s+\} # match 1+ whitespaces then '"units": '
) # end capture group 5
# end capture group 1
(?! # begin negative lookahead
.* # match 0+ chars
\{\s+"name":[ ]" # match '{' then 1+ whitespace chars then '"name": ' then '"'
\1_ # match contents of capture group 1 then '_'
\2_ # match contents of capture group 2 then '_'
\3_ # match contents of capture group 3 then '_'
\4 # match contents of capture group 4
\5 # match contents of capture group 5
) # end of negative lookahead
| # or
\{\s+"name":[ ]" # match '{' then 1+ whitespace chars, then '"name": "
\w+ # match 1+ word chars
_ # match '_'
\w+ # match 1+ word chars
_ # match '_'
\w+ # match 1+ word chars
_ # match '_'
\w+ # match 1+ word chars
(?5) # execute code constructing capture group 6
"""
test_str = ("{\n"
" \"body\": {\n"
" \"metricsArray\": [\n"
" {\n"
" \"name\": \"free-aa-bb2-123x123Profiles\",\n"
" \"units\": \"profiles\",\n"
" \"value\": 14\n"
" },\n"
" {\n"
" \"name\": \"free_aa_bb2_123x123Profiles\",\n"
" \"units\": \"profiles\",\n"
" \"value\": 14\n"
" }\n"
" ],\n"
" \"name\": \"regionxxx\",\n"
" \"timeStamp\": \"2022-01-20T04:58:29.875Z\"\n"
" }\n"
"}\n")
matches = re.finditer(regex, test_str, re.MULTILINE | re.DOTALL | 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