在字符串中查找无限循环(表达式)

时间:2015-08-27 20:15:42

标签: javascript regex

我有一个文本应该检查条件为真的循环,然后我必须替换它们以防止无限循环。我还想知道是否还有其他方法。

当前功能代码:

function whileReplacer(text){
        
        var regex = /while\s*\(([^\)]+)\)/, hasLoops = text.match(regex), whileCondition;
        if(!hasLoops) return text;

        whileCondition = hasLoops[1];

        var isTrueCondition;

        try{
            isTrueCondition = !!eval(whileCondition);
            if(isTrueCondition){ //replacing infinite loop
                text = text.replace(regex, "while(false)");
                console.info("Infinite loop was detected, replaced to =>", text);
            }
        }catch(error){ 
            console.warn("Error evaluating condition =>", whileCondition, error); 
        }

        return text;
    }

    //Text with containing infinite loops

    whileReplacer("while(true){alert(1)}");  //ok

    whileReplacer("while(1);"); //ok

    whileReplacer("while(1+("{"+5)){alert(1)}"); //Condition syntax error
    
    whileReplacer("while(1+')'){alert(1)}"); //Condition syntax error

修改

目前我使用的是/while\([^\)]+\)/.replace("while(false)"),它适用于foo;while(true){};baz;foo;faa;while(1+1){};foo;faa

等示例

但如果搜索中有括号,会发生什么?例如:

while(1+("{"+5)){alert(1)}应将其替换为while(false){alert(1)}

while(1+')'){alert(1)}应将其替换为while(false){alert(1)}

1 个答案:

答案 0 :(得分:1)

使用正则表达式一般都没有办法做到这一点;表达式评估为' true'不能用常规语言描述,所以你不能用正则表达式匹配它们。您可以创建一组您不想运行的表达式,但无法获得完整的覆盖率。