Check if multiple strings exist in another string
You can use any
:
a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]
if any(x in a_string for x in matches):
Similarly to check if all the strings from the list are found, use all
instead of any
.
Check whether a string contains one of multiple substrings
Try parens in the expression:
haystack.include?(needle1) || haystack.include?(needle2)
checking if any of multiple substrings is contained in a string - Python
Here is a possible one-line solution:
print('there is a banned substring inside'
if any(banned_str in url for banned_str in black_list)
else 'no banned substrings inside')
If you prefer a less pythonic approach:
if any(banned_str in url for banned_str in black_list):
print('there is a banned substring inside')
else:
print('no banned substrings inside')
Go: how to check if a string contains multiple substrings?
You can write your own utility function using strings.Contains()
that can work for multiple sub-strings.
Here's an example that returns Boolean (true
/false
) in case of complete / partial match and the total number of matches:
package main
import (
"fmt"
"strings"
)
func checkSubstrings(str string, subs ...string) (bool, int) {
matches := 0
isCompleteMatch := true
fmt.Printf("String: \"%s\", Substrings: %s\n", str, subs)
for _, sub := range subs {
if strings.Contains(str, sub) {
matches += 1
} else {
isCompleteMatch = false
}
}
return isCompleteMatch, matches
}
func main() {
isCompleteMatch1, matches1 := checkSubstrings("Hello abc, xyz, abc", "abc", "xyz")
fmt.Printf("Test 1: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch1, matches1)
fmt.Println()
isCompleteMatch2, matches2 := checkSubstrings("Hello abc, abc", "abc", "xyz")
fmt.Printf("Test 2: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch2, matches2)
}
Output:
String: "Hello abc, xyz, abc", Substrings: [abc xyz]
Test 1: { isCompleteMatch: true, Matches: 2 }
String: "Hello abc, abc", Substrings: [abc xyz]
Test 2: { isCompleteMatch: false, Matches: 1 }
Here's the live example: https://play.golang.org/p/Xka0KfBrRD
Javascript - How to check if a string contains multiple substrings in one condition
I can only think of this:
'use strict';
String.prototype.includes = function (...args) {
return args.filter(str => this.indexOf(str) > -1).length === args.length;
};
var str = 'initcall7773107b-7273-464d-9374-1bff75accc15TopCenter';
if(str.includes('initcall', 'TopCenter')) {
console.log('Do something...');
}
How to check if multiple substrings appear together in a string
strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']
for string in strings:
stringlist = string.split()
word1 , word2 = words
if word1 in stringlist and word2 in stringlist:
print(True)
else:
print(False)
Result
False
True
False
Python check if one of multiple strings contain a substring
If you don't necessarily have to use if-statements, you can do
list(filter(lambda x:'foo' in x, [a,b]))
which will give you a list of strings containing 'foo'
.
So you if you just want to see IF some string contains your keyword, check if the length of this list is bigger 0, like so:
len(list(filter(lambda x:'foo' in x, [a,b]))) > 0
How to test if a string contains one of multiple substrings?
You could use the -match method and create the regex automatically using string.join:
$referenz = @('abc', 'def', 'xyz')
$referenzRegex = [string]::Join('|', $referenz) # create the regex
Usage:
"any string containing abc" -match $referenzRegex # true
"any non matching string" -match $referenzRegex #false
Javascript - How to check if a string contains multiple substrings
Simply use a variable to count the number of "true"
//Main String
var string0 = ' ": {"MATHEMATICS": {"status": "start", "can_start": false}, "READING": {"status": "start", "can_start": false}, "WRITING": {"status": "start", "can_start": false" ';
//Substrings
var substringArray = ['"MATHEMATICS": {"status": "start"', '"READING": {"status": "start"', '"WRITING": {"status": "start"'];
var matchCount = 0;
//Check if Substrings are found in MainString
for (l = 0; l < substringArray.length; l++) {
if (string0.indexOf(substringArray[l]) > -1) {
logger.info("True");
matchCount++;
} else {
logger.info("False");
}
}
if(matchCount == 3){
//do something
logger.info('I did');
} else {
// do some other thing
logger.info('I did not');
}
How to test if a string contains one of the substrings in a list, in pandas?
One option is just to use the regex |
character to try to match each of the substrings in the words in your Series s
(still using str.contains
).
You can construct the regex by joining the words in searchfor
with |
:
>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat
2 dog
3 fog
dtype: object
As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $
and ^
which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.
You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape
:
>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']
The strings with in this new list will match each character literally when used with str.contains
.
Related Topics
How to Get Activerecord Associations via Reflection
Ruby Convert Array into Function Arguments
Install Latest Stable Version of Ruby Using Rbenv
Can Someone Explain Ruby's Use of Pipe Characters in a Block
How to Change the Position of an Array Element
Difference Between Map and Each
Error Installing Homebrew - Brew Command Not Found
How to Password-Protect My /Sidekiq Route (I.E. Require Authentication for the Sidekiq::Web Tool)
Indentation Sensitive Parser Using Parslet in Ruby
Ruby on Rails Gem for Google Map Integration
Add Element to an Array If It's Not There Already
Installing the Postgresql Gem with 'Gem Pq' Fails with Error: Failed to Build Gem Native Extension
Setting Up the Logger in Rails 3
Are There Good Reasons for 'Private' to Work the Way It Does in Ruby