Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get Regex match value(s)? #113

Open
jheliker opened this issue Sep 22, 2021 · 1 comment
Open

How to get Regex match value(s)? #113

jheliker opened this issue Sep 22, 2021 · 1 comment

Comments

@jheliker
Copy link

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?

@bijington
Copy link
Owner

bijington commented Sep 23, 2021

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.

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

No branches or pull requests

2 participants