javascript - 获取反向引用值并修改这些值

标签 javascript jquery regex

您能否解释一下为什么我无法从匹配的正则表达式结果中获取反向引用的值并在有效替换之前对其进行一些修改?

预期的结果是替换例如字符串 ".coord('X','Y')"通过 "X * Y" .但是如果X > 到某个值,将这个值除以 2,然后用这个新值替换。

这里是我目前正在测试的代码:

参见 /*>>1<<*/ & /*>>2<<*/ & /*>>3<<*/ ,这就是我卡住的地方!

我希望能够根据反向引用值在替换之前对反向引用应用修改。

/*>>2<<*/ 之间的区别& /*>>3<<*/就是自调用匿名函数参数

方法/*>>2<<*/是预期的工作解决方案 i可以理解。但奇怪的是,替换不正常,用别名替换 $1 * $2而不是按值(value)...?

您可以测试 jsfiddle

//string to test
".coord('125','255')"

//array of regex pattern and replacement //just one for the example
//for this example, pattern matching alphanumerics is not necessary (only decimal in coord) but keep it as it
var regexes = [ //FORMAT is array of [PATTERN,REPLACEMENT]
    /*.coord("X","Y")*/ [/\.coord\(['"]([\w]+)['"],['"]?([\w:\.\\]+)['"]?\)/g, '$1 * $2']
                  ];
function testReg(inputText, $output) {
    //using regex
    for (var i = 0; i < regexes.length; i++) {
        /*==>**1**/ //this one works as usual but dont let me get backreferences values
         $output.val(inputText.replace(regexes[i][0], regexes[i][2]));

         /*==>**2**/ //this one should works as i understand it
         $output.val(inputText.replace(regexes[i][0], function(match, $1, $2, $3, $4) { 
            $1 = checkReplace(match, $1, $2, $3, $4);
            //here want using $1 modified value in replacement
            return regexes[i][3]; 
        }));

         /*==>**3**/ //this one is just a test by self call anonymous function
         $output.val(inputText.replace(regexes[i][0], function(match, $1, $2, $3, $4) {
            $1 = checkReplace(match, $1, $2, $3, $4);
            //here want using $1 modified value in replacement
            return regexes[i][4];
        }()));

        inputText = $output.val();
    }
}

function checkReplace(match, $1, $2, $3, $4) {
    console.log(match + ':::' + $1 + ':::' + $2 + ':::' + $3 + ':::' + $4);
    //HERE i should be able if lets say $1 > 200 divide it by 2
    //then returning $1 value
    if($1 > 200) $1 = parseInt($1 / 2);
    return $1; 
}​

当然我遗漏了一些东西,但无法得到它!

谢谢你的帮助,问候。

编辑工作方法: 终于明白了,正如 Eric 所提到的:

The key thing is that the function returns the literal text to substitute, not a string which is parsed for backreferences.​​

JSFIDDLE

如此完整的工作代码:(请注意,每个匹配的模式的模式替换都会发生变化,速度代码的优化在这里不是问题,我会保持这样)

 $('#btn').click(function() {
    testReg($('#input').val(), $('#output'));
});

//array of regex pattern and replacement //just one for the example
var regexes = [ //FORMAT is array of [PATTERN,REPLACEMENT] /*.coord("X","Y")*/ 
    [/\.coord\(['"]([\w]+)['"],['"]?([\w:\.\\]+)['"]?\)/g, '$1 * $2']
                     ];

function testReg(inputText, $output) {
    //using regex
    for (var i = 0; i < regexes.length; i++) {
        $output.val(inputText.replace(regexes[i][0], function(match, $1, $2, $3, $4) {
            var checkedValues = checkReplace(match, $1, $2, $3, $4);
            $1 = checkedValues[0];
            $2 = checkedValues[1];
            regexes[i][1] = regexes[i][1].replace('$1', $1).replace('$2', $2);
            return  regexes[i][1];
        }));
        inputText = $output.val();
    }
}

function checkReplace(match, $1, $2, $3, $4) {
    console.log(match + ':::' + $1 + ':::' + $2 + ':::' + $3 + ':::' + $4);
    if ($1 > 200) $1 = parseInt($1 / 2);
    if ($2 > 200) $2 = parseInt($2 / 2);
    return [$1,$2];
}​

最佳答案

.replace(regexes[i][0], function(match, $1, $2) {
    if ($1 > 200) $1 = parseInt($1 / 2);
    if ($2 > 200) $2 = parseInt($2 / 2);
    return $1 + "*" + $2;
})); 

关于javascript - 获取反向引用值并修改这些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987220/

相关文章:

javascript - 如何通过 Javascript Id 选择元素范围

javascript - 如何在 bazaarvoice api 中使用搜索选项

javascript - 从 URL 中删除重复的正斜杠

Java:按照出现的顺序获取字符串中的分隔符

javascript - 未捕获的语法错误 : Invalid regular expression: Nothing to repeat

javascript - 为什么 '+' 在从字符串转换为 float 或整数时像 javascript 中的解析一样,以及它在性能方面有何不同?

javascript - FadeIn 使用 javascript react 组件

javascript - 无法在 Chrome 中设置断点

jquery - 结合jQuery :not and :nth-child selectors

regex - Scala 正则表达式查找和替换