Skip to content

capture returns inconsistent results for optional named group #3093

@elmaimbo

Description

@elmaimbo

Describe the bug
I've just upgraded from JQ version 1.6 to 1.7, and noticed that the capture function is returning an empty string instead of null for an optional named group that doesn't match, but only when no other part of the regex matches.

For example, if your regex contains (?<x>a)?, then if the overall regular expression matches, the output from capture will contain a field x which should either have the value "a" if the capturing group is present, or null if it isn't. The problem is that there are some cases where x has the value "" (i.e. empty string).

To Reproduce
Running the following code shows the issue:
jq -cn '"a","b","c" | capture("(?<x>a)?b?")'

The third line that is output from the command above is wrong because there is no valid case where x can have the value "".

Expected behavior
A capturing group that is followed by "?" should have the value null if the capturing group isn't present.

i.e. The expected result from running the example code above should be:

{"x":"a"}
{"x":null}
{"x":null}

However the output produced by JQ versions 1.7 and 1.7.1 are:

{"x":"a"}
{"x":null}
{"x":""}

i.e. The third line produced an x field with the value "" instead of null.

(FYI JQ 1.6 produces {} as the third line of output, which is also arguably wrong, but IMHO is better than what JQ 1.7 produces.)

Environment (please complete the following information):

  • OS and Version: Linux Ubuntu 23.10
  • jq version 1.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions