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))
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))
The below should work for you assuming Strings is the array that you are searching within:
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.
A more groovyesque approach would be to use inject in combination with metaClass:
I would to love to say:
And the method would be:
If you need containsAny to be present for any future String variable then add the method to the class instead of the object:
EDIT: Here is an update using the Java 8 Streaming API. So much cleaner. Can still be combined with regular expressions too.
Also, if we change the input type to a List instead of an array we can use
items.parallelStream().anyMatch(inputStr::contains)
.You can also use
.filter(inputStr::contains).findAny()
if you wish to return the matching string.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()
ortoUpperCase()
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.You can use String#matches method like this:
Here is one solution :