When a regex had several groups with the same name, a later group that
did not take part in the match overwrote an earlier one that did, so
capture returned null and sub interpolated null instead of the matched
text.
Build the capture object in capture/2 and in the sub reducer by adding
a one-key object for each named group, keeping the value already stored
for that name when the current group did not match. The last group of
each name that took part in the match now wins, empty-string matches
are kept, and the value stays null only when no group of that name
matched. Key order is unchanged. Add a regression test for capture, sub
and gsub.
`f_match` converted each match and capture offset to a codepoint index
by walking from the start of the input, so `match(re; "g")`, `scan`
and `capture(re; "g")` were quadratic in the number of matches.
Count offsets from a cursor at the last converted position instead,
stepping back when a capture starts before it (lookbehind, `\K`).
This commit refactors `splits/2` implementation using `foreach` syntax
and reduces intermediate arrays. This refactoring removes an unnecessary
private (and undocumented) filter `_nwise` and closes#3148.
Instead of just using {"captures":[]}.
sub functions are use captures for replacement expressions.
If we don't populate, captures for empty matches, the replacement
expression is run with an empty object as input instead of an object
containing the named captures with "" as value:
* before:
$ jq -n '"123foo456bar" | gsub("[^a-z]*(?<x>[a-z]*)"; "Z\(.x)")'
"ZfooZbarZnull"
* after:
$ jq -n '"123foo456bar" | gsub("[^a-z]*(?<x>[a-z]*)"; "Z\(.x)")'
"ZfooZbarZ"
---
I also removed a redundant
result = NULL;
if (result) {
...
}
The primary purpose of this commit is to rectify most problems with
`gsub` (and also `sub` with the `g` option), in particular fix#1425 ('\b'),
fix#2354 (lookahead), and fix#2532 (regex == `"^(?!cd ).*$|^cd "`).
This commit also partly resolves#2148 and resolves#1206 in that
`gsub` no longer loops infinitely; however, because the new `gsub`
depends critically on `match/2`, the behavior when regex == `""` is
sometimes non-standard.
The documentation has been updated to reflect the fact that `sub`
and `gsub` are intended to be regular in the second argument.
Also, `_nwise/1` has been tweaked to take advantage of TCO.
./jq --run-tests < tests/onig.test
has been run successfully:
...
Testing 'gsub("a";"b")' at line number 70
Testing 'gsub( "(.*)"; ""; "x")' at line number 74
...
22 of 22 tests passed (0 malformed)