-1

I need help for that as Im beginner what i can do if i want to search on cat with regular expression any number of spaces and check if it in list or not as in match exact ... any help

import re
l = ["hello asma", "     cat", "welcome"]

# iterates over three elements in the list
r = re.compile(r".*cat")
word_search="cat"
if r in l:
    print("yes in")
else:
print("not found")
Jongware
  • 21,058
  • 8
  • 43
  • 86
  • The regex you are using would matches *anything* containing `cat`, not just spaces, as you state. Use `re.compile(r"^\s*cat\s*$")` to match *only* strings consisting of any number of spaces, plus `cat`, plus any number of spaces. See [Reference - What does this regex mean?](https://stackoverflow.com/q/22937618/2564301). – Jongware Apr 22 '18 at 16:00

2 Answers2

0

No need to use re. You can do that with simple list and joins

l = ["hello asma", "     cat", "welcome"]

# iterates over three elements in the list
word_search="cat"

print "\n".join(s for s in l if word_search.lower() in s.lower())

It is so simple and will gives you all the values which contains cat

ramana vv
  • 1,141
  • 11
  • 21
0

If you want to print only exists/("yes in") or not ("not found"),

Please check this code:

l = ["hello asma", "     cat", "welcome"]

# iterates over three elements in the list

word_search="cat"
index=0
for text in l:
    if word_search in text:
        print("yes in")
        break;
    else:
        if(len(l)==index=1):
            print("not found")
    index += 1

#the output is "yes in" //expected output

Another way and smarter solution is:

if word_search in '\n'.join(l):
    print "yes in"
else:
    print "not found"

#the output is "yes in" //expected output
ramana vv
  • 1,141
  • 11
  • 21
  • Your "smarter solution" fails for `l = ['a ca', 'test']` (it returns `True`). The smarter thing is to use `'\n'.join(..)` (unless `word_search` might contain `\n` as well). Also, it seems OP wants to match only *items* consisting of the search word surrounded by any number of spaces. (The question is unclear on that.) – Jongware Apr 22 '18 at 16:12
  • sorry, the smart solution is perfect for string list but solution1 only I forgot to make it index+1 – ramana vv Apr 22 '18 at 17:14
  • make it not found 1 or not fount 2 to debug both at a time – ramana vv Apr 22 '18 at 17:14
  • please check the modified answer – ramana vv Apr 22 '18 at 17:16