Reputation: 530
I have a working template (Google Doc) and have variables with following patterns to be replace with values
{{BASIC SALARY_.Description}}
{{OT1.5.Description}}
{{MEL ALW.Description}}
{{OST ALW.Description}}
{{TRV ALW.Description}}
{{ADV SAL.Description}}
note: I am using soft line break (ctrl+enter) in google doc as I couldn't figure out to detect normal linebreak pattern "\n", "\n", "\r\n" but my result always weird as some line need to be replaced as proper descriptions but some need to be totally nullify (remove whole {{pattern}} together with the line break to avoid empty line)
I have tried out multiple REGEX patterns, googled the online forum
https://github.com/google/re2/wiki/Syntax
Eliminate newlines in google app script using regex
Use RegEx in Google Doc Apps Script to Replace Text
and figure out only soft linebreak is the only way to deal with (identify pattern \v. Please check my sample code as the pattern replace doesn't work as expected.
// code block 1
var doc = DocumentApp.openById(flPayslip.getId());
var body = doc.getBody();
body.replaceText("{{BASIC SALARY_.Description}}", "Basic Salary");
body.replaceText("{{OST ALW.Description}}", "Outstation Allowance");
// code block 2
var doc = DocumentApp.openById(flPayslip.getId());
var body = doc.getBody();
body.replaceText("{{BASIC SALARY_.Description}}", "Basic Salary");
body.replaceText("{{OST ALW.Description}}", "Outstation Allowance");
body.replaceText("{{.*}}\\v+", ""); // to replace soft linebreak
Actual Result of code block 1
Basic Salary
{{OT1.5.Description}}
{{MEL ALW.Description}}
Outstation Allowance
{{TRV ALW.Description}}
{{ADV SAL.Description}}
Actual Result of code block 2:
Basic Salary
Issue: actual result "Outstation Allowance" was removed from regex replacement.
Expected result
Basic Salary
Outstation Allowance
What's the proper regex pattern I should use in my code?
Upvotes: 1
Views: 1743
Reputation: 50382
Try
body.replaceText("{{[^\\v]*?}}\\v+", ""); // No \v inside `{{}}` and not greedy`?`
When you use {{.*}}
, .*
matches everything between the first {{
and the last }}
Basic Salary
{{OT1.5.Description}}
{{MEL ALW.Description}}
Outstation Allowance
{{TRV ALW.Description}}
{{ADV SAL.Description}}
Upvotes: 2