2

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?

2
  • Is that literally the text of the regex you're using at this stage? (\W|^)#replace this please#(\W|$)? If not, can we please see it. Can we also see a real sample line that is tripping you up? Commented Jan 7, 2015 at 20:36
  • Yes, the names can contain spaces and alpha numeric uppercase lower case characters. They are actually columns names from a spreadsheet. I am generating a new document for each row in the sheet, by simply replacing the column names with the row value. It's just normal text in the paragraph of the document, one after another. For example this: #Legal name of aircraft operator# operates as #Trading or operating as#. The description of the operation is located at Annex C of this TSP. Commented Jan 7, 2015 at 23:14

1 Answer 1

1

Having this line in the document:

enter image description here

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:

enter image description here

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.