Regular expression to extract a JSON array Regular expression to extract a JSON array json json

Regular expression to extract a JSON array


Does this match your needs? It should match the category array regardless of its size.

"category":(\[.*?\])

regex101 example


JSON not a regular language. Since it allows arbitrary embedding of balanced
delimiters, it must be at least context-free.

For example, consider an array of arrays of arrays:

[ [ [ 1, 2], [2, 3] ] , [ [ 3, 4], [ 4, 5] ] ]
Clearly you couldn't parse that with true regular expressions.
See This Topic:Regex for parsing single key: values out of JSON in JavascriptMaybe Helpful for you.


Using a set of non-capturing group you can extract a predefined json array

regex answer: (?:\"category\":)(?:\[)(.*)(?:\"\])

That expression extract "category":["Jebb","Bush"], so access the first groupto extract the array, sample java code:

Pattern pattern = Pattern.compile("(?:\"category\":)(?:\\[)(.*)(?:\"\\])");        String body = "{\"device_types\":[\"smartphone\"],\"isps\":[\"a\",\"B\"],\"network_types\":[],\"countries\":[],\"category\":[\"Jebb\",\"Bush\"],\"carriers\":[],\"exclude_carriers\":[]}";Matcher matcher = pattern.matcher(body);assertThat(matcher.find(), is(true));String[] categories = matcher.group(1).replaceAll("\"","").split(",");assertThat(categories.length, is(2));assertThat(categories[0], is("Jebb"));assertThat(categories[1], is("Bush"));