Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a string contains one of multiple substrings

I've got a long string-variable and want to find out whether it contains one of two substrings.

e.g.

haystack = 'this one is pretty long' needle1 = 'whatever' needle2 = 'pretty' 

Now I'd need a disjunction like this which doesn't work in Ruby though:

if haystack.include? needle1 || haystack.include? needle2     puts "needle found within haystack" end 
like image 537
Hedge Avatar asked May 08 '14 00:05

Hedge


People also ask

How do I check if a string contains multiple substrings?

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 .

How do you search for multiple substrings in a string Python?

Using regular expressions, we can easily check multiple substrings in a single-line statement. We use the findall() method of the re module to get all the matches as a list of strings and pass it to any() method to get the result in True or False.

How do you check if a list of substrings are in a string?

Use any() function to check if a list contains a substring in Python. The any(iterable) with iterable as a for-loop that checks if any element in the list contains the substring and returns the Boolean value.


1 Answers

[needle1, needle2].any? { |needle| haystack.include? needle } 
like image 101
seph Avatar answered Oct 09 '22 04:10

seph