I've got a project where I'd like to replicate some of the internal merge field functionality so users can build a link and it'd be really helpful if I could do a case-insensitive string replaceAll.

For example, if I want to replace {!id} or any of it's case variations I could do

return input.replaceAll('\\{![iI][dD]}\\', value);

While I can make do with creating a function to built a regex for any particular input pattern (nevermind the potential issues with script statements) it'd be great if I could emulate how sed works (the 'i' indicates case insensitive). For example:

sed 's/\{!id\}/replacement/i' inputfile.txt

Anyone have any tips on how to accomplish this?


The option to replace case insensitive regex in java is Pattern.CASE_INSENSITIVE, which can also be specified as (?i)


String srcStr = '{!id} value {!Id} is not {!ID}';
String replaceToken = '(?i)\\{!id\\}';
System.debug('REPLACEMENT ' + srcStr.replaceAll(replaceToken, ''));
System.assertEquals('  value  is not ', srcStr.replaceAll(replaceToken, ''));
  • For a 'Mortarboard' encore ;) – techtrekker Nov 9 '12 at 23:08

Just curious can you not convert the string to a particular case?


String ex = 'Upper';



Examples from the official documentation -

String s1 = 'ThIs iS hArD tO rEaD';
System.assertEquals('this is hard to read',

String myString1 = 'abcd';
String myString2 = 'ABCD';
myString1 = 
Boolean result = 
System.assertEquals(result, true);
  • The string gets displayed to the end user, so I'd need to convert it back to it's original case ... – Ralph Callaway Nov 9 '12 at 22:20
  • 1
    Store the original in a string - have a separate variable where you upper/lowercase the values... do your work... replace with original String value? – Salesforce Wizard Nov 9 '12 at 22:36
  • 1
    I would agree to the above comment and since you mentioned the {!Id} field FYI : doing the conversion of Id would result in troubles sometimes if you use the 18 digit ID because 15 digit is a case sensitive ID forceguru.blogspot.com/2010/12/… – Rao Nov 9 '12 at 22:58

You can use other salesforce string methods for the replacement. For example:

String inputString = 'Welcome {!Contact.Name}';
String toReplace = 'contact.name';  //Can use describe methods and get all fields for the relevant object/s

while(inputString.indexOfCaseIgnoreCase(toReplace) != -1){
    Integer indexStartReplace = inputString.indexOfCaseIgnoreCase(toReplace);
    Integer indexEndReplace = indexStartReplace + toReplace.length()
    inputString = inputString.replace(inputString.substring(indexStartReplace, indexEndReplace), '');

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.