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?
Attribution to: Ralph Callaway
Possible Suggestion/Solution #1
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), '');
}
Attribution to: Liron C
Possible Suggestion/Solution #2
Just curious can you not convert the string to a particular case?
say
String ex = 'Upper';
ex.toLowerCase();
(or)
ex.toUpperCase()
Examples from the official documentation -
String s1 = 'ThIs iS hArD tO rEaD';
System.assertEquals('this is hard to read',
s1.toLowerCase());
String myString1 = 'abcd';
String myString2 = 'ABCD';
myString1 =
myString1.toUpperCase();
Boolean result =
myString1.equals(myString2);
System.assertEquals(result, true);
Attribution to: Rao
Possible Suggestion/Solution #3
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 to: techtrekker
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4249