hello guys how would i extract all instances of a substring pattern given a string. e.g given a string templateContent = 'hello adrian , this is for {!Contact.Name} to be delivered to {!Account.ShippingAddress}';. how would i extract all instances of the substrings that have this pattern {!FirstWord.SecondWord}. please note that i am also allowing for punctuation blunders from the users that enter that string. for example a user can type in {!Contact.FirstName}{!Order.Date} (in this case the error being that there is no space between the words. using split would'nt be so effective for this use case from my experience) .

ive been trying to wrap my head around this but i am yet to . Please help . Thank you all.

1 Answer 1


This is a simple "regular expression" situation. You can use the following code as a starting point:

Pattern p = Pattern.compile('\\{!.+?\\}');
string templateContent = 'hello adrian , this is for {!Contact.Name} to be delivered to {!Account.ShippingAddress}';
Matcher m = p.matcher(templateContent);
while(m.find()) {

Where \\{!.+?\\} means:

  • Find {!
  • Followed by any character (.) at least once (+), the minimum number of times possible (?) to the next part.
  • Find }

This will work even when the {!...} is immediately followed by another one.

  • Thank you.. that was exactly what i was trying to get my head around
    – Soji
    Jan 17, 2020 at 14:01
  • this works whenever i use it in the execute anonymous.. but when i try to run it in an apex method from a vf page, it doesnt work ... i get an internal regex error .. any reason why ?
    – Soji
    Jan 17, 2020 at 14:13
  • Invalid regex: Unexpected internal error near index 7 \{!.+?\
    – Soji
    Jan 17, 2020 at 14:14
  • i found my error i guess... i think in the apex controller i was missing the '}' character while in the exec anonymous it was there
    – Soji
    Jan 17, 2020 at 14:35

You must log in to answer this question.

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