I am trying to do something similar in concept to merge fields, basically I want to extract the text that is within "my merge assignment (in the moment is {! the word i want }, but I could change to something different )" so for instance from a string like this:

Hello, this is {!name}, I am {!age} and I live in {!city}

I want to be able to get a List of String that contains the values: name, age, city

I was trying to do something like

String a = 'Hello, this is {!name}, I am {!age} and I live in {!city}';
List<String> b = new List<String>();
List<String> c = new List<String>();
b = a.split('\\{!');
Integer count = 0;
for(String s: b){
    //system.debug(s + ': ' + internal + ' tamano: ' + internal.size());
    if(s.indexOf('\\}') != -1 ){
        String [] internal = s.split('\\}');
        system.debug(': has }');
        system.debug(': not found }');

but for some reason this index is always returning not found.

1 Answer 1


Try to use Patterns and Matchers (regular expression, regex or regexp)

String str = 'Hello, this is {!name}, I am {!age} and I live in {!city}';
pattern p = pattern.compile('\\{!(.*?)\\}');
Matcher m = p.matcher(str);

while(m.find()) {
    system.debug( m.group().substring( 2, m.group().length() - 1) );



  • \\ : backslash is a special symbol, needs to be escaped
  • \\{ : { is a meta char and needs to be escaped.
  • (.*?) : match everything in a non-greedy way and capture it.
  • That works perfectly
    – manza
    Commented May 1, 2016 at 3:53

You must log in to answer this question.

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