能否请您解释一下为什么我不是能够从正则表达式匹配的结果得到的反向引用的值和前有效的替代应用它一些修改?获取反向引用值和modificate这些值
预期的结果是由"X * Y"
替换例如字符串".coord('X','Y')"
。但是,如果X
>某些值,则将该值除以2,然后使用该新值替换。
下面的代码即时通讯目前正在测试:
见/*>>1<<*/
& /*>>2<<*/
& /*>>3<<*/
,这就是即时通讯卡!
我希望能够在这取决于反向引用值的更换前backrefrences申请修改。 /*>>2<<*/
& /*>>3<<*/
之间
不同的只是在自己的呼叫匿名函数PARAM
方法/*>>2<<*/
是预期的工作解决方案i
能理解它。但奇怪的是,更换不能正常工作,取而代之的是别名$1 * $2
而不是价值......?
您可以测试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作为mentionned:
关键的一点是,函数返回的文字文本到 替代品,而不是被解析为反向引用的字符串。
所以,完整的工作代码:(请注意为模式repla水泥将用于速度码每个匹配的模式和优化改变是不是一个问题在这里,我会保持这样的)
$('#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];
}
你能解释一下这个内嵌在你的代码?我无法弄清楚你想要什么。 – Jivings
编辑我的问题并更新了jsfiddle –
@roasted:通过修改'regexes [i] [1]',您可以在第一次之后中断代码。此外,你的工作代码会更好,作为答案 - 它在问题 – Eric