Test if a string contains any of the strings from

2019-01-03 14:08发布

How do I test a string to see if it contains any of the strings from an array?

Instead of using

if (string.contains(item1) || string.contains(item2) || string.contains(item3))

12条回答
霸刀☆藐视天下
2楼-- · 2019-01-03 14:18

The easiest way would probably be to convert the array into a java.util.ArrayList. Once it is in an arraylist, you can easily leverage the contains method.

public static boolean bagOfWords(String str)
{
    String[] words = {"word1", "word2", "word3", "word4", "word5"};  
    return (Arrays.asList(words).contains(str));
}
查看更多
欢心
3楼-- · 2019-01-03 14:18

And if you are looking for case insensitive match, use pattern

Pattern pattern = Pattern.compile("\\bitem1 |item2\\b",java.util.regex.Pattern.CASE_INSENSITIVE);

    Matcher matcher = pattern.matcher(input);
    if(matcher.find() ){ 

}
查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-03 14:19

Since version 3.4 Apache Common Lang 3 implement the containsAny method.

查看更多
三岁会撩人
5楼-- · 2019-01-03 14:22

Try this:

if (Arrays.asList(item1, item2, item3).contains(string))
查看更多
萌系小妹纸
6楼-- · 2019-01-03 14:26
import org.apache.commons.lang.StringUtils;

String Utils

Use:

StringUtils.indexOfAny(inputString, new String[]{item1, item2, item3})

It will return the index of the string found or -1 if none is found.

查看更多
放我归山
7楼-- · 2019-01-03 14:26

If you use Java 8 or above, you can rely on the Stream API to do such thing:

public static boolean containsItemFromArray(String inputString, String[] items) {
    // Convert the array of String items as a Stream
    // For each element of the Stream call inputString.contains(element)
    // If you have any match returns true, false otherwise
    return Arrays.stream(items).anyMatch(inputString::contains);
}

Assuming that you have a big array of big String to test you could also launch the search in parallel by calling parallel(), the code would then be:

return Arrays.stream(items).parallel().anyMatch(inputString::contains); 
查看更多
登录 后发表回答