Reputation: 53
I am trying to do something really really basic. It's just a search and replace using this function, which uses some proprietary Regex I never used before.
https://developers.google.com/apps-script/reference/document/text#replaceText(String,String)
What I am trying to accomplish is simple, run through the whole document and replace placeholders with text. The string to match is in this format:
#replace this please#
By using this pattern:
(\W|^)#replace this please#(\W|$)
copied from the Google Examples found here (https://support.google.com/a/answer/1371417?hl=en)
It works absolutely fine for one exception which bugs me out. If I have 2 or more placeholders on the same line, it won't match any of them.
So if I have something like this:
#replace me please# and some normal text here #replace me too#
None of those 2 will be matched. I am assuming my expression doesn't take this into account, but the documentation is very hard to find for their implementation of regular expressions.
Can anybody help please?
Upvotes: 2
Views: 1611
Reputation: 626806
Having this line in the document:
You may try using the following regex replacement function:
function googleDocsApi27827395() {
var body = DocumentApp.getActiveDocument().getBody();
body.replaceText("(\\W|^)#replace this please#(\\W|$)", "");
}
The result:
The \\W
also matches the adjacent symbol after the first and before the last search word and they are also removed. If you do not need that behavior, remove the (\\W|^)
and (\\W|$)
.
In case you have 3 different strings in between #...#
s, you can use alternations to build the regex:
body.replaceText("#(replace this please|replace me (please|too))#", "");
This line #replace me please# and #replace this please# some normal text here #replace me too#
will turn into and some normal text here
.
Upvotes: 1