Regex - check if input still has chances to become matching

前端 未结 11 1437
天命终不由人
天命终不由人 2020-12-05 00:51

We\'ve got such regexp:

var regexp = /^one (two)+ three/;

So only string like \"one two three\" or \"one two three four\

11条回答
  •  执笔经年
    2020-12-05 01:28

    That's actually quite an interesting question.

    Personally, I'd do it with the RegExp constructor, so the query can be broken down:

    var input = "one ";
    var query = "^one two three";
    var q_len = query.length;
    var match;
    for( var i=1; i<=q_len; i++) {
        match = input.match(new RegExp(query.substr(0,i));
        if( !match) {alert("Pattern does NOT match"); break;}
        if( match[0].length == input.length) {alert("Input is promising!"); break;}
        // else continue to the next iteration
    }
    

    Obviously you can handle the "exact match" case up front to avoid the whole loop thing. If the whole pattern matches the input, then you're all good.

    EDIT: I've just realised that this will not work for groups and stuff. It will fail on account of malformed regexes, but I hope it can serve as a basis for your query.

提交回复
热议问题