1
1
mirror of https://github.com/wader/fq.git synced 2024-11-25 14:12:13 +03:00
fq/internal/gojqx/regexp.go
Mattias Wadman bf7fa07c41 fq: Use go 1.20 and cleanup
Also rename *ex packages to *x
2024-04-01 19:14:10 +02:00

29 lines
705 B
Go

package gojqx
import (
"fmt"
"regexp"
"strings"
)
// from gojq, see https://github.com/itchyny/gojq/blob/main/LICENSE
func CompileRegexp(re, allowedFlags, flags string) (*regexp.Regexp, error) {
if strings.IndexFunc(flags, func(r rune) bool {
return !strings.ContainsAny(string([]rune{r}), allowedFlags)
}) >= 0 {
return nil, fmt.Errorf("unsupported regular expression flag: %q", flags)
}
re = strings.ReplaceAll(re, "(?<", "(?P<")
if strings.ContainsRune(flags, 'i') {
re = "(?i)" + re
}
if strings.ContainsRune(flags, 'm') {
re = "(?s)" + re
}
r, err := regexp.Compile(re)
if err != nil {
return nil, fmt.Errorf("invalid regular expression %q: %w", re, err)
}
return r, nil
}