简体   繁体   English

Googles Apps脚本完全匹配

[英]Googles Apps Script exact match

I'm using this script but it's replacing every instance of a T, A, etc. How do I get it to only replace an exact match? 我正在使用此脚本,但是它将替换T,A等的每个实例。如何获取它以仅替换完全匹配项? Only if it's the letter T and nothing else. 只要是字母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;
  }
}

Thank you :D 谢谢:D

Issue: 问题:

  • String type instead of Regex object: You're providing a String as first argument to String#replace() and expecting a regex type execution. 字符串类型而不是正则表达式对象:您将字符串作为String#replace()第一个参数提供,并期望执行正则表达式类型。 "/^T$/" will be interpreted as a string literal that starts with / , contains ^ , T , and $ and ends with / . "/^T$/"将被解释为以/开头,包含^T$并以/结束的字符串文字。

Solution: 解:

  • Unquoted Regex: Regex literal shouldn't be quoted with " . 不带正则表达式的正则表达式:正则表达式的文字不应使用"

Snippet#1: 片段1:

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

Snippet#2: 片段2:

You can also just use .replace() with a replacer function directly. 您也可以直接将.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);
    });
  })
);

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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