Test If a String Contains Any of the Strings from an Array

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

How to check if a string contains text from an array of substrings in JavaScript?

There's nothing built-in that will do that for you, you'll have to write a function for it, although it can be just a callback to the some array method.

Two approaches for you:

  • Array some method
  • Regular expression

Array some

The array some method (added in ES5) makes this quite straightforward:

if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}

Even better with an arrow function and the newish includes method (both ES2015+):

if (substrings.some(v => str.includes(v))) {
// There's at least one
}

Live Example:

const substrings = ["one", "two", "three"];
let str;

// Setup
console.log(`Substrings: ${substrings}`);

// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}

// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}

Checking if a string contains any of the strings in an array

You can do it like this:

String veryHugeString = ...;
String[] words = new String[] { ... };
boolean foundAtLeastOne = false;
for (String word : words) {
if (veryHugeString.indexOf(word) > 0) {
foundAtLeastOne = true;
System.out.println("Word: " + word + " is found");
break;
}
}

System.out.println("Found at least one : " + foundAtLeastOne);

Using C# to check if string contains a string in string array

Here is how you can do it:

string stringToCheck = "text1";
string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
foreach (string x in stringArray)
{
if (stringToCheck.Contains(x))
{
// Process...
}
}

Maybe you are looking for a better solution... Refer to Anton Gogolev's answer which makes use of LINQ.

Check if a string contains any element of an array in JavaScript

Problem lies in the for loop, which only iterates once since return ends the function, cutting off the for loop in the process. So, you can update the code like so to make the function only return once the for loop has been completed .

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
function checker(value) { var prohibited = ['banana', 'apple'];
for (var i = 0; i < prohibited.length; i++) { if (value.indexOf(prohibited[i]) > -1) { return false; } } return true;}
arr = arr.filter(checker);console.log(arr);

Test if string contains anything from an array of strings (kotlin)

You can use the filter function to leave only those keywords contained in content:

val match = keywords.filter { it in content }

Here match is a List<String>. If you want to get an array in the result, you can add .toTypedArray() call.

in operator in the expression it in content is the same as content.contains(it).

If you want to have case insensitive match, you need to specify ignoreCase parameter when calling contains:

val match = keywords.filter { content.contains(it, ignoreCase = true) }

Detect if string contains any element of a string array

In additional to answer of @Sh_Khan, if you want match some word from group:

let str:String = "house near the beach"
let wordGroups:[String] = ["beach","waterfront","with a water view","near ocean","close to water"]
let worlds = wordGroups.flatMap { $0.components(separatedBy: " ")}
let match = worlds.filter { str.range(of:$0) != nil }.count != 0

how to check if a string contains any element of an array in Java?

The solution for the problem as you presented it is below. However, after writing the whole thing and re-reading your question, I think you are just looking for tags in specific places of the input string (named summary in your example).

If you know that the string will always be of the form "<tag> : blah blah blah", and you have an array of possible tags, you can use more or less the same technique described below, but the regular expression you will need is much simpler: the one below matches a tag surrounded by spaces anywhere in the string, but if the tag will always be at the beginning, you could simply match against this expression

^(tag1)|(tag2)|(tag3)

, which can be generated with:

Stream.of(array).map(Pattern::quote).collect(Collectors.joining(")|(", "^(", ")");

, and then you can define a Pattern and a Matcher as indicated below.


Now, for the original answer:

You could concatenate the string array to create a regular expression (or Pattern, as Java calls them):

String summary = "CD-YTO : SOME RANDOM WORDS";
String[] array = { "CD-YTO", "CD-TYU", "CD-TYP" };

// Create a Stream with the array. Roughly equivalent to a loop
String myPatternString = Stream.of(array)
// Escape any special character in the original words in the array
.map(Pattern::quote)
// Add "positive lookbehind" and "positive lookahead" groups before and after every word.
// This will cause the words to match only when they are surrounded by spaces
// but without including those spaces in the output.
// The "^" and "$" bits take care of words appearing at the beginning or the end of the string
.map(word -> "(?<=^|\\s)" + word + "(?=$|\\s)")
// Combine all elements into a single string
.collect(Collectors.joining(")|(", "(", ")");

The above should give you a string with the form:

"((?<=^|\\s)CD-YTO(?=$|\\s))|((?<=^|\\s)CD-TYU(?=$|\\s))|((?<=^|\\s)CD-TYP(?=$|\\s))"

Because of the Pattern::quote bit, the original strings will probably be further modified so that they are interpreted literally, even if they contain special characters such as parentheses, hyphens, etc. I don't know exactly what Pattern.quote does to escape the strings, but you get the idea.

With that, you can create a Pattern and match it against your input string:

Pattern myPattern = Pattern.compile(myPatternString);
Matcher myMatcher = myPattern.matcher(summary);

while(myMatcher.find()) {
System.out.println(myMatcher.group());
}

Note that Pattern.compile is a expensive operation. If the array is constant and does not change in every execution, you most likely want to store it as a constant in your class and reuse it:

public class MyTagSearcher {

final Pattern thePattern;

public MyTagSearcher(String words...) {
thePattern = Pattern.compile(Stream.of( // etc.));
}

public List<String> matches(String summary) {
final Matcher aMatcher = thePattern.matcher(summary);

// Pre-Java 9
final List<String> retVal = new ArrayList<>();
while(aMatcher.find()) {
retVal.add(aMatcher.group());
}
// or, alternatively, in Java 9 and above
final List<String> retVal = aMatcher.results().map(MatchResult::group).collect(Collectors.toList());

return retVal;
}
}

As a final warning: please note that I haven't tested any of this code; it should generally work but it might require minor tweaks.



Related Topics



Leave a reply



Submit