1

I've got the following regex..

(^\[[.*][[0-9a-zA-Z][0-9a-zA-Z]]*[.*]\])

which is meant to only match non-empty JSON encoded strings like so...

[ { object: HELLO } ]

while excluding "empty" JSON responses such as...

[ ]

These responses may or may not have whitespace in them.

My regex seems to work for some cases i.e..

[ ] <---- does not match.
[ HELLO ] <---- matches.
[ { HELLO } ] <---- does not match.

I'm not so much concerned about the actual validity of the JSON but rather making sure that there is something other than white space within the []

What would be the best way of checking that?

3
  • 2
    What is the context? Why don't you simply parse the JSON? [ { object: HELLO } ] is not JSON btw. Since JSON is contains nested structures, you'd need a recursive regex engine. Commented Aug 9, 2012 at 20:47
  • I agree with @FelixKling: you should be using a dedicated JSON parser. Regex won't be robust enough, and there's LOTS of JSON parsers out there. Commented Aug 9, 2012 at 20:51
  • What programming language are you using? Commented Aug 9, 2012 at 20:51

2 Answers 2

1

Your regular expression is incorrect because you use [...] for both grouping and character classes.

  • Groups are formed using parentheses: (...).
  • Character classes are formed using square brackets: [...].

The expression [.*] is a character class. It does not mean "match zero or more of any character" as you probably intended. It means "match exactly one dot or asterisk".

After fixing these errors, your regular expression can also be simplified:

^\[.*[0-9a-zA-Z]+.*\]$

This does not validate if the JSON is correct. It only checks that the string satisfies the following conditions:

  • Starts with [.
  • End with ].
  • Contains at least one character in 0-9, a-z or A-Z.
Sign up to request clarification or add additional context in comments.

2 Comments

The string [ ] matches your regex. It must have a character which is not a space between the [ ]'s
@Skizit: It works fine. See here: rubular.com/r/4X2OZnHxEm. How are you testing it? Can you post the full code? Also note that "not a space" is not the same as "[0-9a-zA-Z]". Which do you want?
0

why not just check if you have the condition you don't want instead?

^\[\s*\]$

which should check if you have an empty JSON response

ie

  • it starts with [
  • it contains only spaces (0 or more)
  • it ends with ]

1 Comment

The final character should be '$' not '&'. '$' means "end of string". '&' doesn't have any special meaning in regexes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.