批量查找并替换为条件大小写匹配和完全匹配google app脚本,文档,表格 [英] bulk find and replace with a condition case match and exact match google app script,doc,sheet
本文介绍了批量查找并替换为条件大小写匹配和完全匹配google app脚本,文档,表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谢谢.
我有一张数据如下的纸.
I have a sheet with data as follows.
查找 | 替换 | 条件 |
---|---|---|
第10页 | 第10页 | 区分大小写 |
第10页 | 第10页 | 区分大小写 |
ms | 女士 | 完全匹配 |
我想在条件中查找并替换文档中的文本.下面的代码对我来说很好用,但是在任何时候都可以.Willia ms ,它将替换为Willia 女士.
I want to find and replace text in docs with the condition. The below code works fine for me but whenever ex. Williams it replace with WilliaMs.
function replMyText() {
var ss = SpreadsheetApp.openById('1-WblrS95VqsM5eRFkWGIHrOm_wGIPL3QnPyxN_j5cOo');
var sh = ss.getSheetByName('find and replace');
var doc = DocumentApp.getActiveDocument();
var rgtxt = doc.getBody();
var rgrep = sh.getRange('A2:B103');
var repA = rgrep.getValues().filter(r => r.every(c => c.toString()));
repA.forEach(e => rgtxt.replaceText(...e));
}
推荐答案
我们需要捕获正则表达式的组才能正确捕获所有情况,而不仅仅是空格之间的单词.(例如ms."ms" ms,ms!ms?ms!"ms")
We need capture group of regex for properly capturing all cases, not just words between spaces. (e.g. ms. "ms" ms, ms! ms? ms! ‘ms’)
但是,由于 replaceText
不支持捕获组,而 replace
却支持,因此我们需要在 replaceText
replace 派生它>.
But since replaceText
doesnt support capture group while replace
does, we need to derive it using replace
inside replaceText
.
function replMyText() {
var ss = SpreadsheetApp.openById('1-WblrS95VqsM5eRFkWGIHrOm_wGIPL3QnPyxN_j5cOo');
var sh = ss.getSheetByName('find and replace');
var doc = DocumentApp.getActiveDocument();
var rgtxt = doc.getBody();
var rgrep = sh.getRange('A2:C103');
var repA = rgrep.getValues().filter(r => r.every(c => c.toString()));
// Search per paragraph so it won't produce exponential copies per paragraph
var paragraphs = rgtxt.getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
repA.forEach(function(e){
if(e[2] == "match case") {
DocumentApp.getActiveDocument().getBody().replaceText(e[0], e[1]);
}
else if (e[2] == "exact match") {
// Only replace the string in between non [a-zA-Z0-9_]
// Capture string including 2 \W characters around it, then pad them around the replaced string
var replace = "(\\W)" + e[0] + "(\\W)";
var re = new RegExp(replace, "g");
var text = paragraphs[i].getText();
paragraphs[i].replaceText(".*", text.replace(re, "$1" + e[1] + "$2"));
// Replace the ones starting in a paragraph if present
replace = "^" + e[0] + "(\\W)";
re = new RegExp(replace, "g");
text = paragraphs[i].getText();
paragraphs[i].replaceText(".*", text.replace(re, e[1] + "$1"));
}
});
}
}
最新更新测试:
这篇关于批量查找并替换为条件大小写匹配和完全匹配google app脚本,文档,表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文