NOTE: I found some similar questions, but nothing specifically for Python nor this specific scenario.
Here is a small example (working) snippet that searches for strings (from an array of strings) within a larger string.
#!/usr/bin/python
matches = [
"NEEDLE1",
"NEEDLE2",
"N33DL3"
]
haystack = 'this is a haystack, there may or may not be a noodley needle around here. Needless to say I hate N33DL3 people'
for match in matches:
if match in haystack:
print("Found")
Question: Is there a "better" way to do this without having to loop through (for match in matches) each array element?
Edit: The accepted answer works and is fast. Here are the timings:
# Ran the following:
starttime = timeit.default_timer()
for match in matches:
if match in haystack:
print("Found with looping in ", timeit.default_timer() - starttime)
starttime = timeit.default_timer()
if any(match in haystack for match in matches):
print("Found with any() in ", timeit.default_timer() - starttime)
starttime = timeit.default_timer()
if re.search('|'.join(matches), haystack):
print("Found with regex in ", timeit.default_timer() - starttime)
# After many trial runs, the regex continually came out much (much) faster:
('Found with looping in ', 9.5367431640625e-07)
('Found with any() in ', 5.0067901611328125e-06)
('Found with regex in ', 0.0003647804260253906)
any()function. There are many SO questions that show how to do it.any(match in haystack for match in matches)matchesinto a regular expression, then check if the regexp matches.