2

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: [email protected], I need to put that lead into a List.

3 Answers 3

4

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

if(emails.contains(lead.email.substringBefore('@')){
    // add the lead to your special list
}
3

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:

^(abuse@|database@|fbl@|ftp@)

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
{
    get
    {
        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();
}
0

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){
      if(l.email.contains(e)){
          LeadsToAdd.add(l);
      }
   }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .