
[英]Google Apps Script for Multiple Find and Replace in Google Sheets
[英]Google Apps Script Multiple Find and replace regex in Google Sheets
我正在尝试编写Google Apps脚本,以使用正则表达式在Google表格中查找首字母缩写词和缩写。 我有数十个首字母缩写词需要在数千行中替换。 我从堆栈溢出中发现了一些很棒的代码,可以帮助查找和替换字符串,但是对于批量查找正则表达式并替换为字符串没有任何帮助。
通过尝试查找和替换首字母缩写词和缩写,我发现我需要使用带有边界标志的正则表达式来防止它在较大的单词中替换3个字母匹配项。 在下面的示例中,我正在寻找首字母缩写词“ xyz”,并将其替换为“ XYZ”。 但是不希望它与单词“ abc xyz def”匹配。
function runReplaceInSheet(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheetName");
var values = sheet.getDataRange().getValues();
// Replace Acronyms
replaceInSheet(values, '\bxyz\b', 'X Y Z');
// 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;
}
}
据我所知,它仅与字符串而不是正则表达式有关,与'.replace'有关。 我尝试使用双引号转义'\\ b'。
任何帮助,将不胜感激。
使用正则表达式而不是字符串:
replaceInSheet(values, /\bxyz\b/g, 'X Y Z');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.