Gene Vincent Gene Vincent - 1 month ago 8
JSON Question

Extracting a JSON substring with POSIX.2 regex

I need to extract a field value from a JSON string using POSIX.2 extended regular expressions (

man 7 regex
on Linux): eg. from
{"field":"value"}


I'm used to working with Perl-style regex when a simple
/"field":"(.*)"/
would do the trick, but the POSIX regex don't seem to have a notion to express capture groups.

Is there a trick to craft a POSIX pattern that will match exactly the JSON value ?

Answer

In POSIX "basic" regular expressions, capture groups are expressed with \(...\), so what you want is:

"field":"\([^"]*\)"

Note that you have to use [^"]* to prevent the pattern from matching across multiple strings (POSIX regular expressions don't have non-greedy quantifiers).

In "extended" regular expressions, you don't need the backslashes. But you still need to use [^"] instead of . to keep from matching too much.

Comments