Search
Twitter

Entries in matcher (1)

Monday
Sep202010

Regular Expressions in Apex Code

Every once in a while it's very helpful to use regular expressions in your code. The problem is that resources and examples are often scattered. I wanted to give two simple examples of how you can write and test regular expressions in your Apex code inside Salesforce.com.

Return all the numeric characters in a string via regular expression

For the sake of quickly writing and testing this, I've just created a new Lead trigger that runs before insert. I've then set a test input string "input" and I'm using a Pattern object to return the matches in a new string "test". I then print a system debug statement so that I can look in the debug logs to see my results.

trigger myLeadTrigger on Lead (before insert) {

    string input = 'a3f45qq456';

    for (Lead l : Trigger.new)
    {
        //instantiate new Pattern object        
        Pattern p = Pattern.compile('[^0-9]');
        

        //return a string that contains only numeric values from 0-9 from my original input
        String test = p.matcher(input).replaceAll('');
        

        //print a debug statement with my test results
        System.debug(test);

    }

}

Ouput from the debug log shows us that this is working:

16:5:8.981|USER_DEBUG|[12,9]|DEBUG|345456

As you can see, "345456" are the alpha chars from the original string "a3f45qq456".

 

Return all the alphabetical characters in a string via regular expression

For the sake of quickly writing and testing this, I've just created a new Lead trigger that runs before insert. I've then set a test input string "input" and I'm using a Pattern object to return the matches in a new string "test". I then print a system debug statement so that I can look in the debug logs to see my results.

 

trigger myLeadTrigger on Lead (before insert) {

    string input = 'a3f45qq456';

    for (Lead l : Trigger.new)
    {
        //instantiate new Pattern object        
        Pattern p = Pattern.compile('[^a-zA-Z]');
        

        //return a string that contains only numeric values from 0-9 from my original input
        String test = p.matcher(input).replaceAll('');
        

        //print a debug statement with my test results
        System.debug(test);

    }

}

 

Ouput from the debug log shows us that this is working:

6:46:21.762|USER_DEBUG|[14,9]|DEBUG|afqq

As you can see, "afqq" are the alpha chars from the original string "a3f45qq456".