In Javascript I have defined a regular expression and now a user is typing in a string. I want to tell him if his string still could match the RegExp if he continues typing or if he's already on the wrong way. For instance:
var re = /a*b/;
"a".isPrefixOf( re ); // true
"x".isPrefixOf( re ); // false
How could an implementation of isPrefixOf
look like?
Update: Thanks for your answers, making the regex prefix-proof, as suggested by brad, seems to be a good workaround. But I'm still trying to find a general solution.
Maybe this way: We create a new regex with the user input followed by .*
. This regex describes all words that the user still may enter. If the intersection of this created regex and the original regex is empty then the user is already on the wrong way. If it's not, he's doing fine. For instance:
var re = /a*b/;
var sInput = "a";
var reInput = new RegExp( sInput + ".*" );
reIntersection = re.intersect( reInput );
reIntersection.isEmpty(); // false
intersect()
returns a new regex that accepts only word which both re
and reInput
would accept. The function doesn't exist yet but we can implement it using look-ahead:
RegExp.prototype.intersect = function( pattern2 ) {
return new RegExp( '(?=' + this.source + ')' + pattern2.source );
}
What remains open is the isEmpty()
function. How could we check, if a Javascript regex matches any word or if it's empty?