0

I have a string of the form

 _statistics = 
      [
    { Some JSON text here },
.
.
.
];

Basically, I need the text within '[' and '];' . How can i isolate this using RegEx match.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
mhn
  • 2,660
  • 5
  • 31
  • 51
  • [Use a parser](http://stackoverflow.com/a/22773121/21475)! :-) – Cameron Apr 17 '14 at 21:33
  • So...I presume "Some JSON text here" would be JSON? As in, the potential for `{ "foo": [ 1, [ "a" ]] }`? I believe recursion like that will get in the way of regex. – Kirk Woll Apr 17 '14 at 21:33
  • yes.. the JSON text spills over several lines.. but irrespective of what text is between '[' and '];', i need to get it – mhn Apr 17 '14 at 21:36
  • 1
    [`(?<=\[)[^\]]+(?=\])`](http://regex101.com/r/bL1rO5) works, but will fail if you have something like: `[ { "string" : "[I'm in a bracket]" } ]`. – Sam Apr 17 '14 at 21:37
  • @Sam looks like it gives a positive match.. but in C#, i'm not able to isolate the text.. anyways, should solve my real problem:) pls Answer the question so I can mark it as answer – mhn Apr 17 '14 at 21:46

1 Answers1

0

This isn't really the best solution, but anything more intensive and you might as well be using a full JSON parsing library.

(?<=\[)[^\]]+(?=\])

This looks behind for an open bracket ((?<=\[)), then matches 1+ non bracket characters ([^\]]+), and looks ahead for the closing bracket (?=\]). You could optionally forget the lookarounds, and use a capture group instead:

\[([^\]]+)\]

The reason this isn't the best solution, is because it literally looks for text between [ and ]. So JSON like [ { "string" : "[I'm in a bracket]" } ] would return { "string" : "[I'm in a bracket as a match.

Example: Regex101

Sam
  • 20,096
  • 2
  • 45
  • 71