Trouble with regex in Google Docs API text replacement

I’m having a weird problem with the Google Docs API. I’m trying to replace placeholders in a document. The placeholders look like #this is a placeholder#.

I’m using this regex: (\W|^)#replace this please#(\W|$)

It works fine most of the time. But here’s the problem: if there are two or more placeholders on the same line, it doesn’t match any of them. For example:

#replace me# some text here #replace me too#

Neither of these get replaced. I think it’s because of how I wrote the regex, but I’m not sure how to fix it. The docs don’t really explain their regex rules well.

Does anyone know how to make this work for multiple placeholders on one line? I’m stuck and could really use some help. Thanks!

I’ve run into similar issues with the Google Docs API before. The problem likely stems from how the API handles regex matching across multiple occurrences in a single line.

Here’s what worked for me: simplify your regex pattern to #[^#]+#. This matches any text between # symbols without the word boundary assertions. Then, in your code, iterate through all matches in the document content rather than trying to replace them all at once.

Something like this in pseudo-code:

matches = findAllMatches('#[^#]+#', documentContent)
for match in matches:
    replacePlaceholder(match)

This approach gave me more control over the replacement process and avoided the quirks with multiple matches per line. It’s a bit more work on the coding side, but it’s more reliable in my experience.

Hope this helps you out! Let me know if you need any clarification on implementing this method.

I encountered a similar challenge before. Instead of relying on a complicated regex, consider using a simplified pattern like #[^#]+# to capture the placeholder content. This method allows you to process each match individually and avoid issues with multiple occurrences on the same line. The approach might require you to iterate over the matches and replace them one by one, but it gives you greater control over the process. This strategy has proven to be more robust when handling the Google Docs API’s quirks with regex.

hey mate, i think ur problem might be with the \W in ur regex. try using #[^#]+# instead. it’ll match anything between # symbols. then u can loop thru all matches and replace em one by one. worked for me when i had similar issues with the api. good luck!