[SalesForce] Email Template Replace merge field

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.

Best Answer

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

Related Topic