This is basically what I'm trying to accomplish:

I have a Set of strings, for example:

Set<String> emails = new Set<String>{'abuse@','database@','fbl@','ftp@'};

I also have a list of leads, if one of those leads have an email address that starts with any of those strings I need to detect it and save it into another list.

For example if a Lead's email address is: database@test.com, I need to put that lead into a List.


First thing that comes to my mind is to use the String substringBefore(separator) method.

String s1 = 'abuse@localhost';
String s2 = s1.substringBefore('@');
// s2 will contain 'abuse'

From there, you can use the set contains() method to see if the first part of your email matches any of your targets. You would need to adjust your emails set to leave off the @.

This would be performed on each Lead, and could be shortened to a one-liner such as

    // add the lead to your special list

I would use regular expressions for this problem. I know, I know, now you have two problems. Anyway:

public static Boolean startsWithAny(String input, Set<String> substrings)
    if (input == null) return false;
    String expression = '^(' + String.join(new List<String>(substrings), '|') + ')';
    return Pattern.compile(expression).matcher(input).find();

The basic idea above is you simply search for an expression like:


Note that | is an "or" operator in regular expressions, and ^ matches the beginning of a string.

If you want to make it more reusable so you don't have to construct the pattern each time (which consumes CPU), you can statically cache the Pattern. For example, if you put them in a List Custom Setting, you could do:

static Pattern substringPattern
        if (substringPattern == null)
            List<String> substrings = new List<String>(MySetting__c.getAll().keySet());
            String expression = '^(' + String.join(substrings, '|') + ')';
            substringPattern = Patter.compile(expression);
        return substringPattern;
    private set;
public static Boolean containsAnySubstrings(String input)
    return (input == null) ? false : substringPattern.matcher(input).find();

Unfortunately, because you have partial email addresses, you would need to iterate through the set for each email address you want to check. You'd need to do something like the following:

list<lead>LeadsToTest = new List<Lead>(); // <= leads you'll be testing
list<lead>LeadsToAdd = new list<lead>();

For(lead l:LeadsToTest){

   for(string e:emails){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.