Simple string replacement with RegExp and Apex
Kalen Gibbons
Sometimes it's hard to figure out even simple thing in a proprietary language like Apex. So here is a simple solution to a common problem.
How do I replace string elements using Regular Expressions in Apex?
//create expression as Pattern
Pattern dollarPattern = Pattern.compile('[,$]');
//replace all occurrences in a string
dollarPattern.matcher('$1,250.25').replaceAll('')
You need to use Apex's Pattern class to create the regular expression. Then you can replace all matches in the string using the replaceAll() method.
This example takes a dollar formatted string ($1,250.25) and removes the dollar sign and comma to turn it into a number. The result would be 1250.25, perfect for database insertion or what have you.
Posted in How-To