How do I do a case-insensitive replace all for a string?

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?

Answer

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

(http://boards.developerforce.com/t5/Apex-Code-Development/Why-Pattern-CASE-INSENSITIVE-not-detectable/td-p/204337)

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, ''));

Attribution
Source : Link , Question Author : Ralph Callaway , Answer Author : techtrekker

Leave a Comment