Pages

Search Site

Topics

Favorite Links

Archives

Simple string replacement with RegExp and Apex

October 08 2008 by 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.

0 comments Posted in How-To

0 responses to “Simple string replacement with RegExp and Apex”

Leave a Reply