How to Check If a String Contains Any of Some Strings

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

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

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

How to check if a string contains an element from a list in Python

Use a generator together with any, which short-circuits on the first True:

if any(ext in url_string for ext in extensionsToCheck):
print(url_string)

EDIT: I see this answer has been accepted by OP. Though my solution may be "good enough" solution to his particular problem, and is a good general way to check if any strings in a list are found in another string, keep in mind that this is all that this solution does. It does not care WHERE the string is found e.g. in the ending of the string. If this is important, as is often the case with urls, you should look to the answer of @Wladimir Palant, or you risk getting false positives.

How to check if a String contains any of some strings

If you are looking for single characters, you can use String.IndexOfAny().

If you want arbitrary strings, then I'm not aware of a .NET method to achieve that "directly", although a regular expression would work.

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

How to check if a string contains certains letters/characters

I might use String#matches() here, with a regex alternation:

String input = "cpr1210";
if (input.matches("(?i).*(?:cpr|cvr|nr).*")) {
System.out.println("MATCH");
}

If you really wanted to use String#contains(), then you would need to have three separate calls to that method, for each sequence.

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.



Related Topics



Leave a reply



Submit