+ Start a Discussion

Find String between specific characters in Long String

Hi all,


I have a template object that has a field called "Instructions" which is a large string that contains merge fields. I need to create a list of these merge fields so I can loop through a queried record and replace the merge field in the template string with actual information. The instructions are not always the same there are different merge fields on every record.


Here is a simple example and explanation:


String instructions = 'Instructions: Contact Name: {{Contact_Name__c}}, Contact Number: {{Contact_Number__c}}' ;


Is there an simple string method or clever way someone knows of that will allow me to grab the fields between the ' {{ }} '  or any characters for that matter?




The answer is to split the string using String.split. We have a custom email template parser that does this.


The code basically looks like this:


String[] tokens = source.split('\\{\\{|\\}\\}');
// tokens now contains the merge fields.
// Even numbered indexes are literals, odd numbered indexes are merge fields.
// Example: "Hello, {{user.name}}. Nice to meet you."
// Result: ['Hello, ', 'user.name', '. Nice to meet you.']
// Index 0 and 2 are literals, index 1 is a merge field.

This doesn't cover the situation where a user screws up the merge fields (e.g. doesn't open or close correctly, etc). That job is left to the parser to determine if it's broken.


You could also do the same thing using String.indexOf and loop through each merge field and do processing, but I find that a tokenized String array is more flexible for things like creating loops (e.g. a table of data).