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