for this kind of task regex is the best instrument to use. Here is a link to test regex for your needs. You can also read an explanation for regex:
"(!Contract.)(.*)(?=})"
1st Capturing Group (!Contract.)
!Contract matches the characters !Contract literally (case sensitive)
. matches any character (except for line terminators)
2nd Capturing Group (.*)
. matches any character (except for line terminators)
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Positive Lookahead (?=})
Assert that the Regex below matches
} matches the character } with index 12510 (7D16 or 1758) literally (case sensitive)
Apex:
String objectToMatch = 'Contract';
String stringToFind = '{!Contract.Name}';
Pattern pat = Pattern.compile('(!' + objectToMatch + '.)(.*)(?=})');
Matcher mat = pat.matcher(stringToFind);
if(mat.find()){
System.debug(mat.group(2));
}
Debug:
|DEBUG|Name
In this case, you can control for which object you need to parse a field from the input String
.