[jq] Extract named regular expression groups with capture

Created on November 30, 2026

capture returns the text matched by named groups as a JSON object. The example extracts a name and an ID.

printf '%s\n' 'name=alice id=123' | jq -R 'capture("^name=(?<user_name>[a-z]+) id=(?<user_id>[0-9]+)$")'
{
  "user_name": "alice",
  "user_id": "123"
}

-R reads each input line as raw text. Group names such as user_name become output keys. The input label name= is part of the pattern, and alice is the extracted value. The anchors ^ and $ require the entire line to match.

Group values are strings. Use tonumber to turn the ID into a number. -c prints each result on one line.

printf '%s\n' 'name=alice id=123' | jq -Rc 'capture("^name=(?<user_name>[a-z]+) id=(?<user_id>[0-9]+)$") | .user_id |= tonumber'
{"user_name":"alice","user_id":123}

Handle lines that do not match

capture emits nothing for a line without a match. The example skips status=ok.

printf '%s\n' 'name=alice id=123' 'status=ok' | jq -Rc 'capture("^name=(?<user_name>[a-z]+) id=(?<user_id>[0-9]+)$")'
{"user_name":"alice","user_id":"123"}

References

jq