-1

Using the following from Python - Check If Word Is In A String

>>> def findWholeWord(w):
...     return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
... 
>>> findWholeWord('seek')('those who seek shall find')  
<_sre.SRE_Match object at 0x22c1828>
>>> findWholeWord('seek') 
<built-in method search of _sre.SRE_Pattern object at 0x22b8190>
>>> findWholeWord('seek')('those who seek shall find')  
<_sre.SRE_Match object at 0x22c1828>
>>> findWholeWord('seek')('those who shall find') 

Is this an error or this should be the result?

<_sre.SRE_Match object at 0x22c1828>
Community
  • 1
  • 1
badc0re
  • 3,333
  • 6
  • 30
  • 46

2 Answers2

3

This is a funny piece of code, but in python finding a word in a string is actually much simpler. You don't even need a function for this:

 if some_word in some_str.split():
      ....

To find just substrings rather than whole words, omit the split part:

print 'word' in 'funny swordfish'.split()  # False
print 'word' in 'funny swordfish'          # True
georg
  • 211,518
  • 52
  • 313
  • 390
  • well that's what i need not to find them, that's why i used regexp for full match. i keep it in mind for second solution tnx – badc0re May 24 '12 at 09:46
  • @badc0re: you've lost me there. If you want it to return True, just skip the "split" part. `if substr in somestr` will return True for "work" and "working". – georg May 24 '12 at 09:50
2

That match object is the result, and from that you have access to some more functions like

['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__format__'
, '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__'
, '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__','end', 'endpos'
, 'expand', 'group', 'groupdict', 'groups', 'lastgroup', 'lastindex', 'pos', 're'
, 'regs', 'span', 'start', 'string']

so on the returned object you can for example do .span() to get the start and end index of the word you are looking for.

Christian Witts
  • 11,375
  • 1
  • 33
  • 46
  • 1
    To get string, that satisfy full regex, `.group(0)` can be used. And to get only the word in your case, `.group(1)`. This will return string, that satisfy first (). – stalk May 24 '12 at 09:20
  • i could use that too in further development of the app. tnx – badc0re May 24 '12 at 09:23