简体   繁体   中英

Group regex is missing last match

as given in sample code fstr need match all occurence of regEx_C and need to replace with some dynamic value. and make sure each match should have unique value.

in this sample fstr.match(regEX_C) matches 4 match and i need to replace with 1 dynamic value for each.


  1. var_Viablecells_C = X
  2. var_IVCC_C = Y
  3. var_Viablecells_C = Z
  4. var_IVCC_C = Z1

    the value assigned should not match with anyone.


 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)); 

You can just use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM