const regex = /(?&object) # Find the object
####################
(?(DEFINE)
(?<name>
" \s* [^\s"]+ \s* "
)
(?<value>
(?>
(?:
(?&string)
| (?&number)
| (?&object)
| (?&array)
| (?&T_F_N)
)
)
)
(?<string>
"
[^"]*
"
)
(?<number>
\d+
)
(?<array>
\[
(?:
\s* (?&value)
(?>
(?:
\s* , \s*
(?&value)
)*
)
)?
\s* \]
)
(?<T_F_N>
true
| false
| null
)
(?<object>
{
(?:
\s* (?&name) \s* : \s* (?&value)
(?:
\s* , \s* (?&name) \s* :
\s* (?&value)
)*
\s*
)
}
)
)
/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?&object) # Find the object
####################
(?(DEFINE)
(?<name>
" \\s* [^\\s"]+ \\s* "
)
(?<value>
(?>
(?:
(?&string)
| (?&number)
| (?&object)
| (?&array)
| (?&T_F_N)
)
)
)
(?<string>
"
[^"]*
"
)
(?<number>
\\d+
)
(?<array>
\\[
(?:
\\s* (?&value)
(?>
(?:
\\s* , \\s*
(?&value)
)*
)
)?
\\s* \\]
)
(?<T_F_N>
true
| false
| null
)
(?<object>
{
(?:
\\s* (?&name) \\s* : \\s* (?&value)
(?:
\\s* , \\s* (?&name) \\s* :
\\s* (?&value)
)*
\\s*
)
}
)
)
', 'g')
const str = `{
"firstName": "Duke",
"lastName": "Java",
"age": 18,
"streetAddress": "100 Internet Dr",
"city": "JavaTown",
"state": "JA",
"postalCode": "12345",
"phoneNumbers": [
{ "Mobile": "111-111-1111" },
{ "Home": "222-222-2222" }
]
}`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
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 JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions