Reputation: 564
Is there a way to see if a string can be extended with a few characters to match some given regular expression? Can I do it using Regex class? I've googled it for a while and it seems like I should write my own regex parser...
Like Alex said: If the pattern is abc
the string ab
would match my criteria and the string def
or bc
wouldn't. And I want this to work for any regular expression which is unknown at compile time.
Upvotes: 0
Views: 1214
Reputation: 26238
Regular expressions are compiled into decision trees that allow for deciding a match for input of length n in O(n) time. Your custom RE parser could simply count the number of decisions until failure, which when compared with the number of steps necessary for a match, would indicate the "closeness" of the argument to the RE. Assuming you're using fairly simple RE's, and by "extended" mean adding characters to the end of the string, this would be computationally feasible.
Upvotes: 2
Reputation: 4736
I believe you would need to write your own Regex parser. It would need to be able to take an arbitrary Regex and decompose it into elements. For example, it would need to take /abc/
and return { /abc/, /ab/, /a/ }
and check to see if the input matched any of them.
While this might not be too bad for simple expressions like /abc/
, it will become onerous for more complicated expressions like (?<=s)t
that do lookbehind.
Upvotes: 0