Test if a string contains any of the strings from an array

JavaStringIf Statement

Java Problem Overview


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))

Java Solutions


Solution 1 - Java

EDIT: Here is an update using the Java 8 Streaming API. So much cleaner. Can still be combined with regular expressions too.

public static boolean stringContainsItemFromList(String inputStr, String[] items) {
    return Arrays.stream(items).anyMatch(inputStr::contains);
}

Also, if we change the input type to a List instead of an array we can use items.stream().anyMatch(inputStr::contains).

You can also use .filter(inputStr::contains).findAny() if you wish to return the matching string.

Important: the above code can be done using parallelStream() but most of the time this will actually hinder performance. See this question for more details on parallel streaming.


Original slightly dated answer:

Here is a (VERY BASIC) static method. Note that it is case sensitive on the comparison strings. A primitive way to make it case insensitive would be to call toLowerCase() or toUpperCase() on both the input and test strings.

If you need to do anything more complicated than this, I would recommend looking at the Pattern and Matcher classes and learning how to do some regular expressions. Once you understand those, you can use those classes or the String.matches() helper method.

public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
    for(int i =0; i < items.length; i++)
    {
        if(inputStr.contains(items[i]))
        {
            return true;
        }
    }
    return false;
}

Solution 2 - Java

import org.apache.commons.lang.StringUtils;

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html">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.

Solution 3 - Java

You can use String#matches method like this:

System.out.printf("Matches - [%s]%n", string.matches("^.*?(item1|item2|item3).*$"));

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

Try this:

if (Arrays.stream(new String[] {item1, item2, item3}).anyMatch(inputStr::contains))

Solution 7 - Java

Here is one solution :

public static boolean containsAny(String str, String[] words)
{
   boolean bResult=false; // will be set, if any of the words are found
   //String[] words = {"word1", "word2", "word3", "word4", "word5"};
    
   List<String> list = Arrays.asList(words);
   for (String word: list ) {
       boolean bFound = str.contains(word);
       if (bFound) {bResult=bFound; break;}
   }
   return bResult;
}

Solution 8 - Java

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

Solution 9 - Java

A more groovyesque approach would be to use inject in combination with metaClass:

I would to love to say:

String myInput="This string is FORBIDDEN"
myInput.containsAny(["FORBIDDEN","NOT_ALLOWED"]) //=>true

And the method would be:

myInput.metaClass.containsAny={List<String> notAllowedTerms->
   notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}

If you need containsAny to be present for any future String variable then add the method to the class instead of the object:

String.metaClass.containsAny={notAllowedTerms->
   notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}

Solution 10 - Java

We can also do like this:

if (string.matches("^.*?((?i)item1|item2|item3).*$"))
(?i): used for case insensitive
.*? & .*$: used for checking whether it is present anywhere in between the string.

Solution 11 - Java

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()) { 
    ...
}

Solution 12 - Java

If you are seraching for whole words you can do this that works case insensitive.

private boolean containsKeyword(String line, String[] keywords)
{
    String[] inputWords = line.split(" ");
	
	for (String inputWord : inputWords)
	{
		for (String keyword : keywords)
		{
			if (inputWord.equalsIgnoreCase(keyword))
			{
				return true;
			}
		}
	}
	
	return false;
}

Solution 13 - Java

in Kotlin

if (arrayOf("one", "two", "three").find { "onetw".contains(it) } != null){
            doStuff()
        }

Solution 14 - Java

The below should work for you assuming Strings is the array that you are searching within:

Arrays.binarySearch(Strings,"mykeytosearch",mysearchComparator);

where mykeytosearch is the string that you want to test for existence within the array. mysearchComparator - is a comparator that would be used to compare strings.

Refer to Arrays.binarySearch for more information.

Solution 15 - Java

if (Arrays.asList(array).contains(string))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionarowellView Question on Stackoverflow
Solution 1 - JavagnomedView Answer on Stackoverflow
Solution 2 - JavarenanleandrofView Answer on Stackoverflow
Solution 3 - JavaanubhavaView Answer on Stackoverflow
Solution 4 - JavaNicolas FilottoView Answer on Stackoverflow
Solution 5 - JavaRoy KachouhView Answer on Stackoverflow
Solution 6 - JavaÓscar LópezView Answer on Stackoverflow
Solution 7 - JavaserupView Answer on Stackoverflow
Solution 8 - JavaArthur VaïsseView Answer on Stackoverflow
Solution 9 - JavaIvan ArrizabalagaView Answer on Stackoverflow
Solution 10 - JavaChandan KolambeView Answer on Stackoverflow
Solution 11 - JavavsinghView Answer on Stackoverflow
Solution 12 - Javathanos.aView Answer on Stackoverflow
Solution 13 - JavaH.StepView Answer on Stackoverflow
Solution 14 - JavaPrahalad DeshpandeView Answer on Stackoverflow
Solution 15 - JavaGarrett HallView Answer on Stackoverflow