Test if a string contains any of the strings from an array
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;
}
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.
You can use String#matches method like this:
System.out.printf("Matches - [%s]%n", string.matches("^.*?(item1|item2|item3).*$"));
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);