expr icon indicating copy to clipboard operation
expr copied to clipboard

Enable access to matched parts of a regular expression

Open vincentbernat opened this issue 3 years ago • 11 comments

Hey!

It would be nice to be able to access the parts matching a regex when using the matches operator. The captured parts could be assigned to some variables ($1, $2, etc) or to a special matched map indexed by the index and names of matched parts. All this could be done in a provided function, but putting it in the language allows one to get better performance as the regular expressions can be compiled at compile-time instead of at executing time.

vincentbernat avatar Mar 18 '22 08:03 vincentbernat

regular expressions can be compiled at compile-time instead of at executing time.

This is also really easy to do on user side: see ConstExpr

antonmedv avatar Nov 05 '22 18:11 antonmedv

What about adding regexp() builtin? It can be used something like this:

regexp("f.+").FindAllString(str, -1)

antonmedv avatar Nov 05 '22 18:11 antonmedv

As an example, I have a function ClassifySite("something") and a variant ClassifySiteRegex(Exporter.Name, "^([^-]+)-", "$1"). To leverage ConstExpr, I would need the user to wrap the regex into a function, so it would be inconvenient.

As for the builtin you propose, I suppose it returns an array. I was hoping for something a little more magic as it would mean to write something like this:

ClassifySite(regexp("^([^-]+)-").FindAllString(Exporter.Name)[0])

And what happens if there is no match? I would prefer something like:

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

But I would understand that you don't like such magic variables as they make the language non-pure.

vincentbernat avatar Nov 05 '22 22:11 vincentbernat

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

I actually like this idea! Neat! I think it’s understandable what is going on here.

antonmedv avatar Nov 05 '22 22:11 antonmedv

Oh, great! It's how it is in Perl (I think, I don't remember exactly).

vincentbernat avatar Nov 05 '22 23:11 vincentbernat