Fix capture and sub with duplicate group names (#3676)
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.
This commit is contained in:
1 parent
02d1eb9ae5
commit
19752f50a9
2 files changed
+8
-3
No files matched your search
+3
-3
@@ -90,7 +90,7 @@ def test($val): ($val|type) as $vt | if $vt == "string" then test($val; null)
|
||||
elif $vt == "array" and ($val | length) > 1 then test($val[0]; $val[1])
|
||||
elif $vt == "array" and ($val | length) > 0 then test($val[0]; null)
|
||||
else error( $vt + " not a string or array") end;
|
||||
def capture(re; mods): match(re; mods) | reduce ( .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair ({}; . + $pair);
|
||||
def capture(re; mods): match(re; mods) | reduce ( .captures | .[] | select(.name != null) ) as {$name, $string} ({}; . + {($name): ($string // .[$name])});
|
||||
def capture($val): ($val|type) as $vt | if $vt == "string" then capture($val; null)
|
||||
elif $vt == "array" and ($val | length) > 1 then capture($val[0]; $val[1])
|
||||
elif $vt == "array" and ($val | length) > 0 then capture($val[0]; null)
|
||||
@@ -120,8 +120,8 @@ def sub($re; s; $flags):
|
||||
({result: [], previous: 0};
|
||||
$in[ .previous: ($edit | .offset) ] as $gap
|
||||
# create the "capture" objects (one per item in s)
|
||||
| [reduce ( $edit | .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair
|
||||
({}; . + $pair) | s ] as $inserts
|
||||
| [reduce ( $edit | .captures | .[] | select(.name != null) ) as {$name, $string}
|
||||
({}; . + {($name): ($string // .[$name])}) | s ] as $inserts
|
||||
| reduce range(0; $inserts|length) as $ix (.; .result[$ix] += $gap + $inserts[$ix])
|
||||
| .previous = ($edit | .offset + .length ) )
|
||||
| .result[] + $in[.previous:] )
|
||||
|
||||
@@ -99,6 +99,11 @@ capture("(?<a>[a-z]+)-(?<n>[0-9]+)")
|
||||
"xyzzy-14"
|
||||
{"a":"xyzzy","n":"14"}
|
||||
|
||||
# duplicate group names retain matched strings, including empty strings
|
||||
"(?<x>^$)|(?<x>a)|(?<x>b)|c" as $re | map([capture($re), sub($re; "<\(.x)>"), gsub($re; "<\(.x)>")])
|
||||
["a","b","","c","ab"]
|
||||
[[{"x":"a"},"<a>","<a>"],[{"x":"b"},"<b>","<b>"],[{"x":""},"<>","<>"],[{"x":null},"<null>","<null>"],[{"x":"a"},"<a>b","<a><b>"]]
|
||||
|
||||
|
||||
# jq-coded utilities built on match:
|
||||
#
|
||||
|
||||
Reference in new issue
Block a user