【发布时间】:2018-07-26 00:26:22
【问题描述】:
如示例代码中给出的 fstr 需要匹配所有出现的 regEx_C 并且需要替换为一些动态值。并确保每个匹配项都应具有唯一值。
在此示例中 fstr.match(regEX_C) 匹配 4 个匹配项,我需要为每个匹配项替换为 1 个动态值。
-
var_Viablecells_C = X
-
var_IVCC_C = Y
-
var_Viablecells_C = Z
-
var_IVCC_C = Z1
分配的值不应与任何人匹配。
var fstr = '(Math.log(var_Viablecells_C-var_Viablecells_P)/(2-1)+ var_IVCC_C + var_Viablecells_C / var_IVCC_C)';
var regEx_C = /var_(\w+)_C/ig;
var c_val = 5.5;
function putExpValForRegExMatch(fstr, regEx, val) {
var all_match = fstr.match(regEx);
if (null == all_match) return fstr;
console.log(all_match);
for (var i = 0; i < all_match.length; i++) {
console.log(i);
console.log(fstr);
var current_match = regEx.exec(fstr);
if (current_match == null) return fstr;
console.log(current_match);
fstr = replaceRange(fstr, current_match.index, current_match.index + current_match[0].length - 1, '');
fstr = replaceAt(fstr, current_match.index, val);
console.log(fstr);
}
return fstr;
}
function replaceAt(string, index, replace) {
return string.substring(0, index) + replace + string.substring(index + 1);
}
function replaceRange(s, start, end, substitute) {
return s.substring(0, start) + substitute + s.substring(end);
}
console.log(putExpValForRegExMatch(fstr, regEx_C, c_val));
【问题讨论】:
-
我觉得你需要的只是用
return fstr.replace(/var_\w+_C/g, val);替换所有长方法体,请检查jsfiddle.net/ymw4ccaz -
您说您需要为每场比赛应用不同的 val - 请在问题正文中解释要求。
-
@WiktorStribiżew 现在可以试试了吗?
-
太模糊了。请在询问时考虑这种方法:1)“我有
'(Math.log(var_Viablecells_C-var_Viablecells_P)/(2-1)+ var_IVCC_C + var_Viablecells_C / var_IVCC_C)'字符串”,2)“我需要得到".....",因为我想用5.5替换var_Viablecells_C”(???正确???) , 3) “我得到(Math.log(5.5-var_Viablecells_P)/(2-1)+ 5.5 + var_Viablecells_C / 5.5)var_Viablecells_C / 5.5部分不正确,因为我希望它是...”。听起来不错?请编辑澄清。 -
穆克什,为什么换成这样? 1)因为第一个匹配应该替换为
X, the second withY, the third withZ, the fourth withZ1... but what about the next, if any? 2) Or because the first match withViablecells`在Group 1中应该替换为X,那么第二个必须替换为Z,并且第 1 组中的第一个匹配IVCC必须替换为Y,第二个替换为Z1(第三、第四和更多出现呢?)
标签: javascript regex regex-group