how frequently does the letter r appear in:
q: find if a word from a list exist in a string i am trying to find if a sentence contains at least 1 word from a different list of words.
i am able to do this like below code, however my concern goes that the thesentence is a string that is really huge (it comes from an api response), and i have multiple set of list of words to look for that are also quite big, so i am affraid, that using this type of loops will have a big effect in excecution time potentially leading me to a timeout, i am wondering what will be an alternative of this using?
boolean wordfound = false;
list<string> words = new list<string>{word1, word2,....,word n};
string thesentence = hellow word;
for(string s:words){
    if(thesentence.contains(s)){
        wordfound = true;
        break;
    }
}

i am also using the classes pattern and matcher, but i still have to use a loop, so i am not sure if this is truly more efficient or not:
list<string> words = new list<string>{word1, word2,....,word n}; 
string separator = |;
pattern p = pattern.compile(string.join(words, separator));
matcher m = p.matcher(attachment1.body.tostring());
boolean match = false;

while (m.find() == true) {         
    match = true;
    break;
}


a: the pattern, while technically more efficient, suffers from the 1,000,000 iteration limit, outlined in 000005024: why do we get system.exception: regex too complicated error?.
in other words, if bodystring.length() * words.size() exceeds 1,000,000, you need to use contains. otherwise, you can use the pattern. as a matter of practice, you could even use both methods, and determine which to use selectively based on the algorithm i provided here (n.b. im not actually sure if this calculation will work, so please adjust accordingly).
id probably recommend using contains if the number of words is any decent size, because itll not throw the exception, which is actually a type of governor limit (the uncatchable kind of exception).
to clear up a misconception, though, you wouldnt actually call find in a loop if you just wanted the first occurrence, so your actual pattern example could actually just be:
boolean match = m.find();


a: one problem with contains or containsignorecase, is that you can still hit a match on a subset string. for example, searching for low would hit any word that contains the string, like hollow, below, blow, lower, blower, etc. 

user
In that passage, there are one hundred and ten occurrences of the letter "r."
assistant