[SalesForce] Apex: Is there a way to strip out non-alphanumeric characters from a string

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!

Best Answer

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