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.

4
  • How about matches = [x for x in a if x in str]. You could then check the number of matches with len(matches). Commented Mar 3, 2016 at 18:41
  • 4
    Possible duplicate of Python: how to determine if a list of words exist in a string Commented Mar 3, 2016 at 18:41
  • 2
    @Michal Frystacky Didn't came across that one, even if i checked a lot before, stackoverflow is so huge ! thanks ! Commented Mar 3, 2016 at 18:50
  • @ThaoD5 Its no problem, hope it helps! Commented Mar 3, 2016 at 18:53

4 Answers 4

3
matches = [a for a in myArray if a in myStr]

Now check the len() of matches.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks, exactly what i needed, with the if statement example, perfect ;-)
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.

Comments

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.