luca
luca

Reputation: 75

How can I write a regex to extract only digits with a certain string preceding them?

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?

Upvotes: 0

Views: 248

Answers (3)

Michael Berry
Michael Berry

Reputation: 72294

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.

Upvotes: 3

CanSpice
CanSpice

Reputation: 35798

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.

Upvotes: 5

Brian Agnew
Brian Agnew

Reputation: 272297

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.

Upvotes: 6

Related Questions