I have a list of query terms, each with a boolean operator associated with them, like, say:
tom OR jerry OR desperate AND dan OR mickey AND mouse
Okay, now I have a string containing user-defined input, inputStr.
My question is, in Python, is there a way to determine if the string defined by the user contains the words in the “query”?
I have tried this:
if ('tom' or 'jerry' or 'desperate' and 'dan' or 'mickey' and 'mouse') in "cartoon dan character desperate":
print "in string"
But it doesn’t give the output i expect.
As you can see, I don’t care about whether the query terms are ordered; just whether they are in the string or not.
Can this be done? Am I missing something like a library which can help me achieve the required functionality?
Many thanks for any help.
To check whether any of the words in a list are in the string:
Example:
If you use
re.search()as @jro suggested then don’t forget to escape words to avoid collisions with the regex syntax:The above code assumes that
queryhas no meaning other than the words it contains. If it does then assuming that'AND'binds stronger than'OR'i.e.,'a or b and c'means'a or (b and c)'you could check whether a string satisfies query:The above could be written more concisely but it might be less readable:
Example
If you want to reject partial matches e.g.,
'dan'should not match'danial'then instead ofword in stringyoucould use
re.search()and add'\b':