use strict;
my $str = '{
"body": {
"metricsArray": [
{
"name": "free-aa-bb2-123x123Profiles",
"units": "profiles",
"value": 14
},
{
"name": "free_aa_bb2_123x123Profiles",
"units": "profiles",
"value": 14
}
],
"name": "regionxxx",
"timeStamp": "2022-01-20T04:58:29.875Z"
}
}
';
my $regex = qr/ # 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
/msxp;
if ( $str =~ /$regex/g ) {
print "Whole match is ${^MATCH} and its start/end positions can be obtained via \$-[0] and \$+[0]\n";
# print "Capture Group 1 is $1 and its start/end positions can be obtained via \$-[1] and \$+[1]\n";
# print "Capture Group 2 is $2 ... and so on\n";
}
# ${^POSTMATCH} and ${^PREMATCH} are also available with the use of '/p'
# Named capture groups can be called via $+{name}
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 Perl, please visit: http://perldoc.perl.org/perlre.html