0

I have a string (which contains JSON):

[{"type":[236]} , {"type":[2]} , {"type":[95]}, {"other":[33]}, {"other":[44]}]

I want to use a regex to extract only the TYPE numbers, so that the output is the following string:

[236 , 2 , 95]

How can I do this?

KatieK
  • 13,586
  • 17
  • 76
  • 90
luca
  • 75
  • 3

3 Answers3

6

Why do you specifically want a regexp ? If the input is JSON, I'd use a JSON parser to handle this. It'll be built specifically to parse the above and handle edge cases etc.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
5

Why not parse it with a JSON parser, then pull out all of the values from the resulting structure that point to type keys? Using a regular expression to parse text that's in a defined format like JSON is a good way to go crazy.

Community
  • 1
  • 1
CanSpice
  • 34,814
  • 10
  • 72
  • 86
3

You could potentially do it with a regex, but a much better way would be to use a JSON parser:

  • It's arguably clearer in your code that you're dealing with JSON if you're using a dedicated JSON parser (regexes on their own can be rather cryptic)
  • It'll be a heck of a lot easier to use
  • It will be much more reliable, especially in corner cases where a regex might fall down (a properly implemented JSON parser should handle all cases correctly.)

So yes, you could probably hack together a regex to do it, but given the fact that there's a comprehensive JSON parser (the one I've linked to) freely available there's little sense in doing it the regex way.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216