0

I am struggling to find a certain word in a sentence. For instance, If I have a this sentence 'look toward cage again'

import re
pattern = r'again'
text = 'look toward cage again'
matchOB = re.search(pattern , text)
if match0B:
   print('True')

This code returns True, however

pattern = r'aga'
text = 'look toward cage again'
matchOB = re.search(pattern , text)
if match0B:
   print('True')

This code also returns True. I want to return only if it is completely matched with word not with characters.

It would be really appreciated if it is explained in detail.

TIshow
  • 918
  • 4
  • 12
  • 27
  • 1
    Do you have to use Regex? Since there are ways to do this with just pure Python – kstullich Jan 17 '18 at 22:01
  • 3
    Regex isn't needed here... `if pattern in text.split():` – glibdud Jan 17 '18 at 22:02
  • Oh I also tried to make sure without Regex , however I did not have that idea to use text.split(). Thank you so much for all ! – TIshow Jan 17 '18 at 22:05
  • But that will not work well with any punctuation, as it will not find the word "punctuation" in this comment. Or "comment" for that matter. – Jongware Jan 17 '18 at 22:11

1 Answers1

0

You can use the pattern (assuming words can only be comprised of alphabetics):

\b[A-Za-z]+\b

If you want to match digits too:

\b[A-Za-z0-9]+\b
  • \b matches empty string at the end of word

  • [A-Za-z0-9]+ matches one or more characters from [A-Za-z0-9]

As a side note, if you want to include _ too, you can use the token \w:

\b\w+\b
heemayl
  • 39,294
  • 7
  • 70
  • 76