badc0re badc0re - 3 months ago 14
Python Question

Check If Word Is In A String errors

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>

Answer

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.

Comments