Sietse Sietse - 9 months ago 96
Javascript Question

Regex to match a JSON String

I am building a JSON validator from scratch, but I am quite stuck with the string part. My hope was building a regex which would match the following sequence found on String Sequence

My regex so far is:


It does match the criteria with a backslash following by a character and an empty string. But I'm not sure how to use the UNICODE part.

Is there a regex to match any UNICODE character expert " or \ or control character? And will it match a newline or horizontal tab?

The last question is because the regex match the string "\t", but not " " (four spaces, but the idea is to be a tab). Otherwise I will need to expand the regex with it, which is not a problem, but my guess is the horizontal tab is a UNICODE character.

Thanks to Jaeger Kor, I now have the following regex:


It appears to be correct, but is there any way to check for control characters or is this unneeded as they appear on the non-printable characters on The input to validate is always text from a textarea.

Update: the regex is as following in case anyone needs it:


Answer Source

For your exact question create a character class

# Matches any character that isn't a \ or "

And then you can just add * on the end to get 0 or unlimited number of them or alternatively 1 or an unlimited number with +




Also there is this below, found at under the library tab when searching for json

# Note that everything is atomic, JSON does not need backtracking if it's valid
# and this prevents catastrophic backtracking

This should match any valid json, you can also test it at the website above


Link to the regex