【问题标题】:Group regex is missing last match组正则表达式缺少最后一场比赛
【发布时间】:2018-07-26 00:26:22
【问题描述】:

如示例代码中给出的 fstr 需要匹配所有出现的 regEx_C 并且需要替换为一些动态值。并确保每个匹配项都应具有唯一值。

在此示例中 fstr.match(regEX_C) 匹配 4 个匹配项,我需要为每个匹配项替换为 1 个动态值。


  1. var_Viablecells_C = X

  2. var_IVCC_C = Y

  3. var_Viablecells_C = Z

  4. 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 with Y, the third with Z, the fourth with Z1... but what about the next, if any? 2) Or because the first match with Viablecells`在Group 1中应该替换为X,那么第二个必须替换为Z,并且第 1 组中的第一个匹配 IVCC 必须替换为 Y,第二个替换为 Z1(第三、第四和更多出现呢?)

标签: javascript regex regex-group


【解决方案1】:

你可以使用string.prototype.replace()

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;

output = fstr.replace(regEx_C,c_val)

【讨论】:

  • 这种方法不需要捕获组。
  • 我知道,但需要为每场比赛应用不同的 val
猜你喜欢
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 2016-05-16
相关资源
最近更新 更多