Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions builtin.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 5 additions & 9 deletions builtin.jq
Original file line number Diff line number Diff line change
Expand Up @@ -157,18 +157,14 @@ def scan($re; $flags):
else
[.captures[].string]
end;
def splits($re; $flags):
.[foreach (match($re; $flags + "g"), null) as {$offset, $length}
(null; {start: .next, end: $offset, next: $offset + $length})];
def splits($re; $flags): _splits($re; $flags + "g"; false)[];
def splits($re): splits($re; null);
def split($re; $flags): [splits($re; $flags)];
def split($re; $flags): _splits($re; $flags + "g"; false);
def sub($re; str): sub($re; str; null);
def sub($re; str; $flags):
reduce match($re; $flags) as {$offset, $length, $captures}
({s: ., r: []};
reduce ($captures | _captures | str) as $s
(.i = 0; .r[.i] += .s[.next:$offset] + $s | .i += 1) |
.next = $offset + $length) | .r[] + .s[.next:] // .s;
. as $s | _splits($re; $flags; true) as [$ps, $cs] |
[range($cs | length) as $i | [$cs[$i] | str | $ps[$i] + .]] |
(transpose[] | add + $ps[-1]) // $s;
def gsub($re; str): sub($re; str; "g");
def gsub($re; str; $flags): sub($re; str; $flags + "g");

Expand Down
29 changes: 29 additions & 0 deletions cli/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7053,6 +7053,35 @@
"aabcABC☆★☆ABCabc"
"abcABC☆★☆ABCabc"

- name: sub and gsub functions with multiple outputs and unmatched captures
args:
- -c
- '[sub("(?<x>[ab])"; "1", "2")], [gsub("(?<x>[ab])"; if .x == "a" then "1", "2" else "3" end)], gsub("(?<x>a)|b"; "<\(.x)>")'
input: '"abcab"'
expected: |
["1bcab","2bcab"]
["13c13","2c2"]
"<a><null>c<a><null>"

- name: splits, sub, and gsub functions against multibyte characters
args:
- -c
- '[splits("☆+")], [splits("b|★"; "i")], split("[☆★]*"; null), sub("☆+"; "-"), gsub("(?<x>[☆★])"; .x + .x)'
input: '"a☆B☆☆c★"'
expected: |
["a","B","c★"]
["a☆","☆☆c",""]
["","a","","B","","c","",""]
"a-B☆☆c★"
"a☆☆B☆☆☆☆c★★"

- name: sub function type error
args:
- 'sub("x"; "y")'
input: '{}'
error: |
match("x"; null) cannot be applied to: object ({})

- name: match function with empty matches
args:
- -c
Expand Down
11 changes: 11 additions & 0 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,13 @@ func (c *compiler) compileFunc(e *Func) error {
true,
-1,
)
case "_splits":
return c.compileCallInternal(
[3]any{c.funcSplits, len(e.Args), e.Name},
e.Args,
true,
-1,
)
default:
return c.compileCall(e.Name, e.Args)
}
Expand Down Expand Up @@ -1318,6 +1325,10 @@ func (c *compiler) funcMatch(v any, args []any) any {
return funcMatch(v, args[0], args[1], args[2], &c.regexpCache)
}

func (c *compiler) funcSplits(v any, args []any) any {
return funcSplits(v, args[0], args[1], args[2], &c.regexpCache)
}

func (c *compiler) compileObject(e *Object) error {
c.appendCodeInfo(e)
if len(e.KeyVals) == 0 {
Expand Down
90 changes: 67 additions & 23 deletions func.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ func init() {
"strptime": argFunc1(funcStrptime),
"now": argFunc0(funcNow),
"_match": argFunc3(nil),
"_splits": argFunc3(nil),
"_captures": argFunc0(funcCaptures),
"error": {argcount0 | argcount1, false, funcError},
"halt": argFunc0(funcHalt),
Expand Down Expand Up @@ -1989,35 +1990,13 @@ func funcMatch(v, re, fs, testing any, cache *sync.Map) any {
} else {
name = "match"
}
var flags string
if fs != nil {
var ok bool
flags, ok = fs.(string)
if !ok {
return &func2TypeError{name, v, re, fs}
}
}
s, ok := v.(string)
if !ok {
return &func2TypeError{name, v, re, fs}
}
restr, ok := re.(string)
if !ok {
return &func2TypeError{name, v, re, fs}
}
r, err := compileRegexp(restr, flags, cache)
s, r, n, err := prepareMatch(name, v, re, fs, cache)
if err != nil {
return err
}
if testing == true {
return r.MatchString(s)
}
var n int
if strings.ContainsRune(flags, 'g') {
n = -1
} else {
n = 1
}
xs := r.FindAllStringSubmatchIndex(s, n)
res, names := make([]any, len(xs)), r.SubexpNames()
for i, x := range xs {
Expand Down Expand Up @@ -2053,6 +2032,71 @@ func funcMatch(v, re, fs, testing any, cache *sync.Map) any {
return res
}

// funcSplits splits the string by the matches of the regular expression. When
// capturing is true, it returns the named captures of the matches as well.
func funcSplits(v, re, fs, capturing any, cache *sync.Map) any {
s, r, n, err := prepareMatch("match", v, re, fs, cache)
if err != nil {
return err
}
xs := r.FindAllStringSubmatchIndex(s, n)
res := make([]any, len(xs)+1)
var prev int
for i, x := range xs {
res[i], prev = s[prev:x[0]], x[1]
}
res[len(xs)] = s[prev:]
if capturing != true {
return res
}
captures, names := make([]any, len(xs)), r.SubexpNames()
for i, x := range xs {
capture := make(map[string]any)
for j, name := range names {
if name == "" {
continue
}
if x[j*2] < 0 {
capture[name] = nil
} else {
capture[name] = s[x[j*2]:x[j*2+1]]
}
}
captures[i] = capture
}
return []any{res, captures}
}

func prepareMatch(name string, v, re, fs any, cache *sync.Map) (string, *regexpMatcher, int, error) {
var flags string
if fs != nil {
var ok bool
flags, ok = fs.(string)
if !ok {
return "", nil, 0, &func2TypeError{name, v, re, fs}
}
}
s, ok := v.(string)
if !ok {
return "", nil, 0, &func2TypeError{name, v, re, fs}
}
restr, ok := re.(string)
if !ok {
return "", nil, 0, &func2TypeError{name, v, re, fs}
}
r, err := compileRegexp(restr, flags, cache)
if err != nil {
return "", nil, 0, err
}
var n int
if strings.ContainsRune(flags, 'g') {
n = -1
} else {
n = 1
}
return s, r, n, nil
}

func compileRegexp(re, flags string, cache *sync.Map) (*regexpMatcher, error) {
key := [2]string{re, flags}
if r, ok := cache.Load(key); ok {
Expand Down