How To: RegEx for balanced JSON

Related to another conversation, this regular expression pattern will help determine if a JSON string is balanced. I used free-space mode with comments because, otherwise, it just looks like a bunch of punctuation marks. :slight_smile:

(?x)					# FREE SPACE MODE

# BEGIN - Match a JSON object
(
\\{						# Opening brace
([^\\[{\\]}]|(?R))*
\\}						# Closing brace
)
# END

|

# BEGIN - Match a JSON array
(
\\[						# Opening bracket
([^\\[{\\]}]|(?R))*
\\]						# Closing bracket
)
# END

As code without comments:

dim rx as new RegEx
rx.SearchPattern = _
"(?xmi-Us)					(\\{						([^\\[{\\]}]|(?R))*\\}						)|(\\[						([^\\[{\\]}]|(?R))*\\]						)"
dim rxOptions as RegExOptions = rx.Options
rxOptions.LineEndType = 4

dim match as RegExMatch = rx.Search( sourceText )

I should note that this pattern is imperfect. If a string within the JSON string contains a brace or bracket, it will fail.

OK, here’s the version that will ignore braces/brackets within strings:

(?x)					# FREE SPACE MODE

# Define a string
(?(DEFINE)
	(?<str>"(?:\\\\["\\\\]|[^"])*")
)

# BEGIN - Match a JSON object
(
\\{						# Opening brace
((?&str)|[^\\[{\\]}]|(?R))*
\\}						# Closing brace
)
# END

|

# BEGIN - Match a JSON array
(
\\[						# Opening bracket
((?&str)|[^\\[{\\]}]|(?R))*
\\]						# Closing bracket
)
# END