how to check whether a string contains words specified in a set

  • how to check whether a string contains any element specified in a set of elements? say for eg: how to check whether below statement 'I got two dogs and a cat'

    contains words specified in set {dog,cat,parrot}

  • You can use the Pattern and Matcher class, constructing the regexp pattern from the values of the set, or you could loop through each value in the set and compare it to a value. Solutions are ordered from most flexible to least flexible.

    Pattern and Matcher

    Pattern p = Pattern.compile(String.join(new List<String>(keyWords),'|'));
    Matcher m = p.matcher(targetString);
    if(m.find()) { ... }
    • Can be modified to match whole words only, can be made case insensitive, and isn't affected by punctuation.

    Search and Compare

    Boolean matches = false;
    for(String key:keyWords) {
        if(targetString.indexOf(key)>-1) {
            matches = true;
    • Matches any part of any word; matching whole words would be rather difficult without a complex condition statement.

    I think a `set` has not a method called `containsAny`, but a `string`. And `containsAny` checks for any character and not for the word.

    You can not use String.join with a Set sorry ^^

    Thanks for reminding me of that. You can, however, convert a set to a string on the fly, so I've updated the answer to reflect this.

    Solution with Pattern/matcher won´t work if for example a keyword contains round brackets. Invalid regex error

  •  String test='There are two dogs and a cat';
     set<string> a=new Set<string>{'dog','cat','pat'};
     boolean check=false;
    List<String> lsttest=test.split(' ');
     for(String s: lsttest){

    You can use the above also to find whether string contains any word

  • The following code works pretty well without any loop :

    Set<String> keyWords = new Set<String>{'dog','cat','pat'};
        System.debug('It contains dog!');

    It is completely unnecessary to serialize the set before calling `contains`, as it is a `Set` instance method. Besides, this doesn't answer OP's question, as you are comparing to a single string only, whereas he wants to find words of that string in the set.

    Oh yeah my bad sorry

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used