3

I'm using regular expression in my project, and have an array like this :

myArray = [
    r"right",
    r"left",
    r"front",
    r"back"
]

Now I want to check if the string, for example

message = "right left front back"

has more than one match in this array, my purpose here is to have an if being true only if there is only one word matching one of the array.

I tried a lot of things, like this one

if any(x in str for x in a):

but I never make it work with a limited amount.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
ThaoD5
  • 183
  • 3
  • 14
  • How about `matches = [x for x in a if x in str]`. You could then check the number of matches with `len(matches)`. – zondo Mar 03 '16 at 18:41
  • 4
    Possible duplicate of [Python: how to determine if a list of words exist in a string](http://stackoverflow.com/questions/21718345/python-how-to-determine-if-a-list-of-words-exist-in-a-string) – Michal Frystacky Mar 03 '16 at 18:41
  • 2
    @Michal Frystacky Didn't came across that one, even if i checked a lot before, stackoverflow is so huge ! thanks ! – ThaoD5 Mar 03 '16 at 18:50
  • @ThaoD5 Its no problem, hope it helps! – Michal Frystacky Mar 03 '16 at 18:53

4 Answers4

3

You can use sum here. The trick here is that True is calculated as 1 while finding the sum. Hence you can utilize the in directly.

>>> sum(x in message for x in myArray)
4
>>> sum(x in message for x in myArray) == 1
False

if clause can look like

>>> if(sum(x in message for x in myArray) == 1):
...     print("Only one match")
... else:
...     print("Many matches")
... 
Many matches
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
3
matches = [a for a in myArray if a in myStr]

Now check the len() of matches.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
2
any(x in message for x in myArray)

Evaluates to True if at least one string in myArray is found in message.

sum(x in message for x in myArray) == 1

Evaluates to True if exactly one string in myArray is found in message.

pp_
  • 3,435
  • 4
  • 19
  • 27
2

If you are looking for one of the fastest ways to do it use intersections of sets:

mySet  = set(['right', 'left', 'front', 'back'])
message = 'right up down left'

if len(mySet & set(message.split())) > 1:
    print('YES')
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419