I'm working in Python, using any() like so to look for a match between a String[]
array and a comment pulled from Reddit's API.
Currently, I'm doing it like this:
isMatch = any(string in comment.body for string in myStringArray)
But it would also be useful to not just know if isMatch
is true, but which element of myStringArray
it was that had a match. Is there a way to do this with my current approach, or do I have to find a different way to search for a match?
match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. The function searches for some substring in a string and returns a match object if found, else it returns none.
Use re. match() to check if a string matches a pattern A pattern specifies a sequence of characters that can be matched to a string and follows the regular expression syntax in Python. re. match(pattern, string) tests if the regex pattern matches string .
If you need to know if a string matches a regular expression RegExp , use RegExp. prototype. test() . If you only want the first match found, you might want to use RegExp.
findall. findall() is probably the single most powerful function in the re module. Above we used re.search() to find the first match for a pattern. findall() finds *all* the matches and returns them as a list of strings, with each string representing one match.
For python 3.8 or newer use Assignment Expressions
if any((match := string) in comment.body for string in myStringArray):
print(match)
You could use next
with default=False
on a conditional generator expression:
next((string for string in myStringArray if string in comment.body), default=False)
The default is returned when there is no item that matched (so it's like any
returning False
), otherwise the first matching item is returned.
This is roughly equivalent to:
isMatch = False # variable to store the result
for string in myStringArray:
if string in comment.body:
isMatch = string
break # after the first occurrence stop the for-loop.
or if you want to have isMatch
and whatMatched
in different variables:
isMatch = False # variable to store the any result
whatMatched = '' # variable to store the first match
for string in myStringArray:
if string in comment.body:
isMatch = True
whatMatched = string
break # after the first occurrence stop the for-loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With