温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Googles Apps Script exact match
google-apps-script google-sheets javascript regex

javascript - Googles Apps脚本完全匹配

发布于 2020-03-27 11:16:23

我正在使用此脚本,但是它将替换T,A等的每个实例。如何获取它以仅替换完全匹配项?只要是字母T,别无其他。

function runReplaceInSheet(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Underlevel");
  //  get the current data range values as an array
  //  Fewer calls to access the sheet -> lower overhead 
  var values = sheet.getDataRange().getValues();  

  // Replace
  replaceInSheet(values, "/^T$/", '=image("https://i.imgur.com/Dxl893F.png")');
  replaceInSheet(values, 'A', '=image("https://i.imgur.com/omc7F9l.png")');
  replaceInSheet(values, 'R', '=image("https://i.imgur.com/12ZmSp3.png")');
  replaceInSheet(values, 'M', '=image("https://i.imgur.com/kh7RqBD.png")');
  replaceInSheet(values, 'H', '=image("https://i.imgur.com/u0O7fsS.png")');
  replaceInSheet(values, 'F', '=image("https://i.imgur.com/Hbs3TuP.png")');

  // Write all updated values to the sheet, at once
  sheet.getDataRange().setValues(values);
}

function replaceInSheet(values, to_replace, replace_with) {
  //loop over the rows in the array
  for(var row in values){
    //use Array.map to execute a replace call on each of the cells in the row.
    var replaced_values = values[row].map(function(original_value) {
      return original_value.toString().replace(to_replace,replace_with);
    });

    //replace the original row values with the replaced values
    values[row] = replaced_values;
  }
}

谢谢:D

查看更多

查看更多

提问者
Ryan King
被浏览
171
TheMaster 2019-07-03 22:34

问题:

  • 字符串类型而不是正则表达式对象:您要提供一个字符串作为第一个参数,String#replace()并期望执行正则表达式类型。"/^T$/"将被解释为一个字符串字面启动与/,包含^T以及$ 和结束与/

解:

  • 不带正则表达式的正则表达式:正则表达式的文字不应使用"

片段1:

/^T$/    //or new RegExp('^T$')

片段2:

您也可以直接使用.replace() 替换功能。

var range = sheet.getDataRange();
var replaceObj = {
  //to_replace: imgur id
  T: 'Dxl893F',
  A: 'omc7F9l',
};
var regex = new RegExp('^(' + Object.keys(replaceObj).join('|') + ')$', 'g');// /^(T|A)$/
function replacer(match) {
  return '=image("https://i.imgur.com/' + replaceObj[match] + '.png")';
}
range.setValues(
  range.getValues().map(function(row) {
    return row.map(function(original_value) {
      return original_value.toString().replace(regex, replacer);
    });
  })
);

参考文献: