一致した正規表現の結果から後方参照の値を取得できず、効果的な置換の前に変更を適用できない理由を説明してください。
期待される結果は、たとえば文字列".coord('X','Y')"
を。に置き換えること"X * Y"
です。ただし、X
>をある値にした場合は、この値を2で割ってから、この新しい値を代わりに使用します。
ここに、現在テストしているコードがあります。
&&を参照してください、これは私が立ち往生しているところ/*>>1<<*/
です/*>>2<<*/
!/*>>3<<*/
後方参照値に応じて、置換前に後方参照に変更を適用できるようにしたいと思います。
/*>>2<<*/
&の違い/*>>3<<*/
は、自己呼び出しの無名関数パラメーターです。
この方法は、理解できるように/*>>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;
}
確かに私は何かが足りないのですが、それを手に入れることができません!
よろしくお願いします。
作業方法の編集: エリックが述べたように、最後にそれを入手してください:
重要なことは、関数が、後方参照のために解析される文字列ではなく、置換するリテラルテキストを返すことです。</ p>
したがって、完全に機能するコード:(一致するパターンごとにパターンの置換が変更され、速度コードの最適化はここでは問題になりません。そのように維持します)
$('#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];
}