Skip to content

Add a regexp builtin for capture groups and matching - #1012

Open
wozhenbang2004 wants to merge 2 commits into
expr-lang:masterfrom
wozhenbang2004:add-regexp-builtin
Open

wozhenbang2004 wants to merge 2 commits into
expr-lang:masterfrom
wozhenbang2004:add-regexp-builtin

Conversation

@wozhenbang2004

Copy link
Copy Markdown

Related to #229.

Add the proposed regexp(pattern) builtin, returning *regexp.Regexp so expressions can use Go's matching and capture-group methods:

let parts = regexp("^([^-]+)-").FindStringSubmatch(Exporter.Name);
len(parts) > 0 ? parts[1] : "unknown"

The function uses the existing builtin type checking and method dispatch. Invalid patterns return an evaluation error. Each call creates a fresh regexp, so changing a returned regexp with Longest() cannot affect later evaluations of the same program. This adds the builtin API; it does not precompile constant patterns.

Added tests for capture groups, no matches, replacement, invalid arguments and patterns, dynamic patterns, and state isolation with optimization on and off.

Validation: go test ./..., go test -race . ./builtin, the debugger test, go vet ./..., GOARCH=386 go build, and the repository coverage script (91.8%) pass on Go 1.26.11.

Return a fresh *regexp.Regexp through the existing typed builtin interface. Cover capture groups, dynamic patterns, invalid input and per-evaluation state isolation.

Related to expr-lang#229.

Signed-off-by: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com>
Describe evaluation errors and fresh regexp values, with matching and capture-group examples.

Related to expr-lang#229.

Signed-off-by: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com>
@antonmedv

Copy link
Copy Markdown
Member

I think this API is very Go centric. Lets figure out the API which will be ok for exampkle for JS backend. I was thinkjing about using something like $1.

@wozhenbang2004

Copy link
Copy Markdown
Author

The $1 form fits the original example in #229 better than returning a Go regexp.Regexp:

Exporter.Name matches "^([^-]+)-" && ClassifySite($1)

I’d keep matches boolean and make $1, $2, etc. available only on the right side of that &&, after the match on the left succeeds. An optional group that didn’t participate would be nil. A failed match would still short-circuit. That gives both backends the same Expr-facing capture values without a shared “last match” variable. Is that the scope you had in mind?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants