[英]Google Apps Script Multiple Find and replace regex in Google Sheets
I'm trying to write a Google Apps Script to find acronyms and abbreviations within Google sheets using regular expressions. 我正在尝试编写Google Apps脚本,以使用正则表达式在Google表格中查找首字母缩写词和缩写。 I have dozens of acronyms that need to be replaced over thousands of rows.
我有数十个首字母缩写词需要在数千行中替换。 I have found some great bits of code from stack overflow that help find and replace strings, but nothing for bulk finding regex and replacing with strings.
我从堆栈溢出中发现了一些很棒的代码,可以帮助查找和替换字符串,但是对于批量查找正则表达式并替换为字符串没有任何帮助。
With trying to find and replace acronyms and abbreviations I found I needed to use regex with the boundary flag to prevent it replacing 3 letter matches within bigger words. 通过尝试查找和替换首字母缩写词和缩写,我发现我需要使用带有边界标志的正则表达式来防止它在较大的单词中替换3个字母匹配项。 In the example below, I'm looking for the acronym "xyz" and to replace it with "XYZ".
在下面的示例中,我正在寻找首字母缩写词“ xyz”,并将其替换为“ XYZ”。 But don't want it do match on the word "abc xyz def".
但是不希望它与单词“ 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;
}
}
From my little understanding it's to do with '.replace' only working with Strings and not Regular expressions. 据我所知,它仅与字符串而不是正则表达式有关,与'.replace'有关。 I've tried escaping the '\\b', using double quotes.
我尝试使用双引号转义'\\ b'。
Any help would be appreciated. 任何帮助,将不胜感激。
使用正则表达式而不是字符串:
replaceInSheet(values, /\bxyz\b/g, 'X Y Z');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.