Determines if any words in a list are in a given phrase. - Java java.lang

Java examples for java.lang:String Contain

Description

Determines if any words in a list are in a given phrase.

Demo Code


//package com.java2s;

import java.util.regex.Pattern;

public class Main {
    /**// ww w .  j a v a  2s  .co m
     * Determines if any words in a list are in a given phrase. A word is defined as what is between spaces.
     * @param words iterable of words, separated by whitespace, that may or may not be in phrase
     * @param phrase phrase to be examined
     * @param caseSensitive true if words are matched case sensitively, false otherwise
     * @return true if any words are in the phrase with whitespace on either side, false otherwise<br\>
     * e.g. wordsInPhrase(Iterable("a"), "a bear", false) returns true and wordsInPhrase(Iterable("a"), "the bear") returns false, even though "bear" contains "a" 
     */
    public static boolean wordsInPhrase(Iterable<String> words,
            String phrase, Boolean caseSensitive) {

        for (String word : words) {
            word = Pattern.quote(word);
            String[] regexes = new String[] { ".*\\s" + word,
                    ".*\\s" + word + "\\s.*", word + "\\s.*", word };
            for (String regex : regexes) {
                Pattern pattern = caseSensitive ? Pattern.compile(regex)
                        : Pattern.compile(regex, Pattern.CASE_INSENSITIVE
                                | Pattern.UNICODE_CASE);
                if (pattern.matcher(phrase).matches()) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Determines if any words in a list are in a given phrase, case insensitively. A word is defined as what is between spaces.
     * @param words iterable of words, separated by whitespace, that may or may not be in phrase
     * @param phrase phrase to be examined
     * @return true if any words are in the phrase with whitespace on either side, false otherwise<br\>
     * e.g. wordsInPhrase(Iterable("A"), "a bear") returns true and wordsInPhrase(Iterable("A"), "the bear") returns false, even though "bear" contains "a" 
     */
    public static boolean wordsInPhrase(Iterable<String> words,
            String phrase) {
        return wordsInPhrase(words, phrase, false);
    }
}

Related Tutorials