Oh my god. It's full of code!

Extracting Strings with RegEx in Salesforce Apex

Hey everyone. This is just another quick tip type of deal. It’s pretty easy to replace strings with Apex and regular expressions, but it’s a little bit harder to extract that string. In this example I want to extract a project number from an email subject line. The project number will be between { } braces. So how exactly do I got about doing this? Well it looks a bit like this.

string subject = 'this is a test {12312-D} email subject [dfasdfa]';
Pattern p = Pattern.compile('\\{([^}]*)\\}');
Matcher m = p.matcher(subject);
if (m.find()) 

First I create a string to search. then I create matching pattern by using the pattern class and my nifty little regular expression. Remember to use Java style regular expressions! then I do a match against the subject line. After that I want to check and see if there was a match, and if so I debug out the first grouping. the 0th grouping contains the match with the brackets, and the 1st contains the text without. So there you have it. Just modify the regular expression to suit your needs and you should be on your way. Have fun!

4 responses

  1. Cam Mathers

    If you don’t want the culy braces in the result try the following pattern:

    Pattern p = Pattern.compile(‘(?i)(?m)(?<=\\{).*?(?=\\})');

    This also includes case insensitive (?i), multi line (?m). It uses a positive look behind and a positive look ahead.

    July 15, 2013 at 5:06 am

  2. Wow! In the end I got a webpage from where I know how to truly take valuable facts concerning my
    study and knowledge.

    September 13, 2013 at 3:51 am

  3. Murali

    Thanks, Saved me a lot of time 🙂

    March 10, 2014 at 9:31 am

  4. Anonymous

    Thanks a lot!

    July 21, 2017 at 5:09 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s