8

In order to store results in the newly released (Winter 16') Platform Cache, I need an alphanumeric string, but currently have a String with the report name that I'm attempting to store, some of which have spaces, hyphens, parenthesis, etc. (i.e. "Sales - Actual Results (TY)").

I'm not sure in APEX how I would strip all these unwanted characters from the string to convert it into the alphanumeric key that I need.

Please & Thank you!

4 Answers 4

16

I would use the following Regular Expression: '[^a-zA-Z0-9]'

Pattern nonAlphanumeric = Pattern.compile('[^a-zA-Z0-9]');
Matcher matcher = nonAlphanumeric.matcher('Sales - Actual Results (TY)');
system.debug(matcher.replaceAll('')); // output: SalesActualResultsTY

Demo

2
  • 3
    Is this faster-executing than system.debug('Sales - Actual Results (TY)'.replaceAll('[^a-zA-Z0-9]', '')); , especially in a loop through lots of strings that need stripping? I find the one-liner easier to read, but if I need to do this style for performance, I would.
    – k..
    Jul 31, 2017 at 17:27
  • 2
    Probably not...You could ask a separate question if you are curious.
    – Adrian Larson
    Jul 31, 2017 at 17:28
3

I know this doesn't exactly answer your question (removing invalid characters from your string), but since you're using Platform Cache, why not use a hash for your key? It's unique and you don't have to worry about which characters are in the string you're generating the hash from.

public String generateHash(String inputString) {
    Blob targetBlob = Blob.valueOf(inputString);
    Blob hash = Crypto.generateDigest('SHA1', targetBlob);
    return EncodingUtil.convertToHex(hash);
}

Example usage:

String reportName = "Sales - Actual Results (TY)";
String cacheKey = generateHash(reportName);
// Value of cacheKey is "050bc0bde14099279e556202652e982c8a47f2b8"

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_crypto.htm

2
  • Do you know if there are any added performance cost since taking the time to encrypt it? Dec 18, 2015 at 23:40
  • 1
    @Xtremefaith SHA1 isn't actually an encryption algorithm. It's a hashing algorithm (a one-way operation). There is actually a performance savings, especially over Regular Expressions. SHA1 is exceptionally fast while Regular Expressions, even compiled, are notoriously slow (though, and excellent tool when used appropriately). I ran a performance test with 10,000 iterations for each, the regular expression above versus using a SHA1 hash, the average time for each was: Regular Expressions: 1.111 milliseconds SHA1 Hash: 0.0019 milliseconds
    – neoscrib
    Dec 20, 2015 at 6:50
1

Once I used this

String yourString = 'may the force be with @you^';

String specialChars = '&|^|@';   // in this string, write all the special chars you want to get ride of, pipe separated


for(integer i=0; i<specialChars.split('|').size(); i++)
{
   yourString = yourString.replace(specialChars.split('|')[i], '');
}
System.debug('Special-chars free string is >>>>>>>>>>>>>>>>>>>>>>>>>>>>> ' + yourString);

For your case

String yourString = 'Sales - Actual Results (TY)';

String specialChars = '(|)|-| |';  


for(integer i=0; i<specialChars.split('|').size(); i++)
{
    yourString = yourString.replace(specialChars.split('|')[i], '');
}


System.debug('Special-chars free string is >>>>>>>>>>>>>>>>>>>>>>>>>>>>> ' + yourString);
1

I think it is worth mentioning that the platform key maximum size is 50 characters, so be careful when using Strings as keys.

1
  • I couldn't find this in the documentation, but it is true. "Invalid key: max key length is 50" if you try to use something longer. Oct 26, 2023 at 7:09

You must log in to answer this question.

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