Regex.exec对于不同的输入表现不同

时间:2014-12-31 15:58:35

标签: javascript regex

对于以下javascript方法

function evalExpression(expression) {
        if (expression) {
            console.log('Before Expression: ' + expression)
            var pattern = new RegExp(/\[(\w+)\]/gi);
            result = pattern.exec(expression);
            while (result != null) {
                for (var index = 1; index < result.length; index++) {
                    var oldKey = result[index];
                    console.log('match:' + oldKey);
                    var replacer = 'UNDEF';
                    expression = expression.replace(oldKey, replacer);
                    console.log('After expression: ' + expression);
                }
                // Get the next match.
                result = pattern.exec(expression)
            }
        }
    }

当我将输入传递为

evalExpression("[RelationshipRefToEMID] != null ) && ([RelationshipRefToEMID] <>3448001");

exec 的迭代只发生一次

但是我打电话给

evalExpression("[RelationshipRefToMID] != null ) && ([RelationshipRefToMID] <>3448001");

然后迭代发生两次

以下是每次执行的结果

Before Expression: [RelationshipRefToEMID] != null ) && ([RelationshipRefToEMID] <>3448001
match:RelationshipRefToEMID
After expression: [UNDEF] != null ) && ([RelationshipRefToEMID] <>3448001

Before Expression: [RelationshipRefToMID] != null ) && ([RelationshipRefToMID] <>3448001
match:RelationshipRefToMID
After expression: [UNDEF] != null ) && ([RelationshipRefToMID] <>3448001
match:RelationshipRefToMID
After expression: [UNDEF] != null ) && ([UNDEF] <>3448001

我努力了,但我无法理解这种行为。

感谢。

0 个答案:

没有答案