bijington/expressive

How to get Regex match value(s)?

Opened this issue · 1 comments

Hello -

First off, thanks so much for the great library!

I'm trying to test the Regex function, and I have the following regular expression: (\d+)(?!.*\d)") which matches the last number of the input. I see Expressive is correctly accepting my regex by doing the following:

Regex("Test", "(\d+)(?!.*\d)")
Which returns False (there are no numbers in "Test")

and

Regex("Test123", "(\d+)(?!.*\d)")
Which returns True

What I really need, however, is to get the first match returned back.

So, in the first example above, I'd have an empty string returned instead of False, and in the second example above, I'd have "123" returned instead of True. Is this possible?

Hey @jheliker thank you for the compliment and the issue.

Sadly the Regex function is quite limited and only returns whether there is a match or not. I am more than happy to add in more functionality for more complex Regex functions. I don't know what a suitable name would be for Regex as I wouldn't want to break existing people. I would be keen to look over this and try to cover as many scenarios as possible (https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=net-5.0#performing-regular-expression-operations).

But for now you could create a new function and register it to provide the functionality that you want. I think the following would work for you:

context.RegisterFunction(
    "Regex",
    (parameters, arguments) =>
    {
        return new System.Text.RegularExpressions.Regex(parameters[1].Evaluate(arguments) as string).Match(parameters[0].Evaluate(arguments) as string);
    }, 
    true);

NOTE this will replace the existing Regex function. If you wanted to use both then you would need to register with a different name or make your overriding function more complex so it could handle both scenarios.