14

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?

4

5 に答える 5

3

ここでの最善の策は、正規表現の接頭辞を証明することだと思います。あなたが与えた例については、/a*b/おそらく を使用できると思います/a*b?/.test(userinput)。より複雑なパターンの場合、これはますます難しくなる可能性がありますが、一連のオプションの量指定子 ( ) で各部分式をネストすることで実行できると思います?。例えば:

/a*bcd*e/

接頭辞の正規表現は次のようになります。

/a*(b(c(d*e?)?)?)?/

少し面倒ですが、問題をかなりうまく解決できると思います。

于 2009-01-06T14:05:04.947 に答える
-1

これを行う 1 つの方法は、テキスト ボックスの onKeyUp イベントにフックし正規表現に対してテキストをテストすることです。 私の仮定は、もちろん、正規表現のマッチングを行いたいということです。 これがまさにあなたが必要としているものかどうかはわかりませんが、実際にはあなたのコードです:

"a".isPrefixOf( re ); // true

後続の「b」文字も必要なため、一致することはありません (正規表現を変更する必要がある場合があります)。たとえば、このコードは、この形式に一致するすべての文字列に対してテストします。

a-n(n)-b

コードは次のとおりです。ページとして保存し、ブラウザにロードします。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="it">
<body>
    <input type="text" size="20" id="txtData" onkeyup="showResult()" />
    <div id="dvResult" />
</body>
</html>
<script type="text/javascript">
//<![CDATA[

    theRegExp = /^a\-\d{1,2}\-b$/;

    function isPrefixOf( aText, aRegExp )
    {
        return aRegExp.test( aText );
    }

    function showResult()
    {
        res = document.getElementById( "dvResult" );
        res.innerHTML = isPrefixOf( document.getElementById( "txtData" ).value, theRegExp ) ? "Correct" : "Bad input";
    }

//]]>
</script>
于 2009-01-06T13:32:05.667 に答える
-2

まず、正規表現を次のように定義します: var re = new RegExp(/^(regexp here)$/);

onKeypress イベントで、次のように正規表現を確認します。

text.match(regexp) - テキストは入力された文字列です。

これは明らかですか?

于 2009-01-06T13:09:05.993 に答える