4

I have an email template which uses merge fields from a custom object. For reasons difficult to explain here, I have to write my own code to read the body of the email template in Apex, replace merge fields with the objects field value. For eg:

plainTextBody.replaceAll('{!File_User__c.Name}', fileUser.Name);

However, this throws an exception

System.StringException: Invalid regex: Illegal repetition {!File_User__c.Name}

I search on the net and the resolution is to escape the curly braces. I have tried using \{!File_User__c.Name\} but it doesn't work.

My questions are 1. How to we parse merge fields without the error above? 2. Is there a better way of parsing email template?

Thank you.

3

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_System_String_replaceAll.htm

The document for ReplaceAll method of string functions

and document for replace method of string functions

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_System_String_replace.htm

So ReplaceAll expects a regex .For your case i would suggest you to use simple replace and should satisfy the requirement

plainTextBody.replace('{!File_User__c.Name}', fileUser.Name);

All the matching substrings of the string will be replaced

  • Thank you. Replace works. So I will have to basically run a loop while the match is found and replace the strings. That would work as of now. – RajeshShah Oct 9 '13 at 13:21
  • hey no need to run any loop as i mentioned .Just use replace and you should be good.wherever the string is found it will automatically replace .Hope this helped you – Mohith Shrivastava Oct 10 '13 at 8:23
  • What if I have multiple email templates with different merge field values? – Testing_SFDC Dec 4 '15 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.