Apex: Is there a way to strip out non-alphanumeric characters from a string?

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


I know this doesn't exactly answer your question (removing invalid characters from your string), but since your 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

Tags:

Apex