Note that there are some explanatory texts on larger screens.

plurals
  1. POCheck if string is a prefix of a Javascript RegExp
    text
    copied!<p>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:</p> <pre><code>var re = /a*b/; "a".isPrefixOf( re ); // true "x".isPrefixOf( re ); // false </code></pre> <p>How could an implementation of <code>isPrefixOf</code> look like?</p> <p><strong>Update:</strong> 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.</p> <p>Maybe this way: We create a new regex with the user input followed by <code>.*</code>. 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:</p> <pre><code>var re = /a*b/; var sInput = "a"; var reInput = new RegExp( sInput + ".*" ); reIntersection = re.intersect( reInput ); reIntersection.isEmpty(); // false </code></pre> <p><code>intersect()</code> returns a new regex that accepts only word which both <code>re</code> and <code>reInput</code> would accept. The function doesn't exist yet but we can implement it using look-ahead:</p> <pre><code>RegExp.prototype.intersect = function( pattern2 ) { return new RegExp( '(?=' + this.source + ')' + pattern2.source ); } </code></pre> <p>What remains open is the <code>isEmpty()</code> function. How could we check, if a Javascript regex matches any word or if it's empty?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload