问题
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()+"$"," ");
回答1:
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;
}
}
}
If you want to practice with regular expressions then www.regexr.com is very handy.
来源:https://stackoverflow.com/questions/30105989/replace-first-occurrence-of-text-using-replacetextsearchpattern-replacement