问题描述
我正在尝试使用函数replaceText(searchPattern, replacement)
替换Google Doc中第一个出现的段落,但是我似乎找不到正确的RegEx表达式.如果有人可以帮助我,我将非常感激.
I am trying to replace the first occurrence of a paragraph in Google Doc using the function replaceText(searchPattern, replacement)
, but I can't seem to find the right RegEx expression.If someone could help me I would really appreciate it.
body.replaceText("^"+paragraph.getText()+"$"," ");
推荐答案
body.ReplaceText()函数替换模式的所有实例,而不仅仅是第一个实例(链接).
The body.ReplaceText() function replaces all instances of a pattern, not just the first instance ( link ).
更好的选择可能是遍历段落以查找具有匹配文本的第一个段落,例如:
A better option may be to loop through the paragraphs to find the first with matching text, like so:
function deleteParagraph(textToRemove) {
var body = DocumentApp.getActiveDocument().getBody();
// gets all paragraphs as an array
var paragraphs = body.getParagraphs()
for (var i = 0; i < paragraphs.length; i++){
if (paragraphs[i].getText() === textToRemove){
paragraphs[i].clear()
Logger.log(textToRemove + " was removed")
//stops it looping through any more paragraphs
break;
}
}
}
如果您想使用正则表达式练习,那么www.regexr.com非常方便.
If you want to practice with regular expressions then www.regexr.com is very handy.
这篇关于使用replaceText(searchPattern,替换)替换第一次出现的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!