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.

1 Answer 1



The document for ReplaceAll method of string functions

and document for replace method of string functions


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, 2013 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 Oct 10, 2013 at 8:23
  • What if I have multiple email templates with different merge field values? Dec 4, 2015 at 7:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .