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.


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.

| improve this answer | |
  • Thank you.. that was exactly what i was trying to get my head around – olaitan adesoji Jan 17 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 ? – olaitan adesoji Jan 17 at 14:13
  • Invalid regex: Unexpected internal error near index 7 \{!.+?\ – olaitan adesoji Jan 17 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 – olaitan adesoji Jan 17 at 14:35

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.