Parsing an Email Subject in email-to-case using RegEx for EXACT matching

Parsing out an Email Subject in email-to-case using RegEx for EXACT matching

Salesforce's On-Demand Email Handler Service can be further enhanced using a case trigger to better identify the type of case that is being created. Inherently not the best way for customers to create cases (Web-to-Case, Communities are much better alternatives), but sometimes this is the path of least resistance.

This solution shows how to parse out an email subject and search for a list of potential strings to match against to help categorize your case (and potentially route to appropriate service agents). Workflow rules or Process Builder flows will not be able to do exactly this.

Follow the steps below to parse an Email Subject in email-to-case using RegEx

Step 1:

Create some Custom Labels with comma-separated lists of strings to match against.  For example, let's say we want to distinguish between emails asking for support versus sales. The best approach is obviously to have 2 separate email addresses, but let's say you have just one target email address.

EmailSubjectSupport = “help,support,assistance”
EmailSubjectSales = “buy, new, order, cost”

Step 2:

Create picklist values in Case.Type for "Support" and "Sales"

Step 3:

Create Case Trigger (beforeInsert) and use this code snippet below:

public static void setCaseType(List<Case> records) {
    String searchWords;
    List<String> strings;
    for(Case c : records) {
        searchWords = Label.EmailSubjectSupport;
        strings = searchWords.split(',');
        if (isStringInTarget(strings, c.Subject)) {
            c.Type = 'Support'; continue; 
        }
        searchWords = Label.EmailSubjectSales;
        strings = searchWords.split(',');
        if (isStringInTarget(strings, c.Subject)) {
            c.Type = 'Sales’; continue;
        }
    } // end for loop
} // end setCaseType

public static Boolean isStringInTarget(List<String> strings, String target) {
    String strRegEx = '(?i)\\b(';
    // case insensitive and exact match only 
    for (String s : strings) {
        strRegEx = strRegEx + s + '|'; // build up a list of strings using | separator 
    }
    strRegEx = strRegEx.removeEnd('|'); // get rid of the last OR
    strRegEx = strRegEx + ')\\b';
    Matcher matcher=Pattern.compile(strRegEx).matcher(target);
    Boolean result= matcher.find();
    return result;
}

Related Articles

Responses