How to search for a word (exact match) within a string?

15,975

Solution 1

You want Python's re module:

>>> import re
>>> regex = re.compile(r"\sthis\s") # \s is whitespace
>>> # OR
>>> regex = re.compile(r"\Wthis\W")
>>> # \w is a word character ([a-zA-Z0-9_]), \W is anything but a word character
>>> str2 = 'researching this'
>>> str3 = 'researching this '
>>> bool(regex.search(str2))
False
>>> regex.search(str3)
<_sre.SRE_Match object at 0x10044e8b8>
>>> bool(regex.search(str3))
True

I have a hunch you're actually looking for the word "this", not "this" with non-word characters around it. In that case, you should be using the word boundary escape sequence \b.

Solution 2

It looks like you want to use regular expressions, but you are using ordinary string methods. You need to use the methods in the re module:

import re
>>> re.search("[^a-z]"+str1+"[^a-z]", str2)
>>> re.search("[^a-z]"+str1+"[^a-z]", str3)
<_sre.SRE_Match object at 0x0000000006C69370>
Share:
15,975
Zenvega
Author by

Zenvega

Updated on June 04, 2022

Comments

  • Zenvega
    Zenvega almost 2 years

    I am trying to substring search

    >>>str1 = 'this'
    >>>str2 = 'researching this'
    >>>str3 = 'researching this '
    
    >>>"[^a-z]"+str1+"[^a-z]" in str2
    False
    
    >>>"[^a-z]"+str1+"[^a-z]" in str3
    False
    

    I wanted to True when looking in str3. what am I doing wrong?

  • Admin
    Admin over 12 years
    I think the idea is to account for word boundaries to ensure that an exact match is found (e.g., str1 in "researching thistles" should return False).
  • Zenvega
    Zenvega over 12 years
    Thanks. if I want to search 'researching' using re.search("[^a-z]"+'researching'+"[^a-z]", str3), I am not getting any object value. What am I doing wrong?
  • robert
    robert over 12 years
    @Pradeep see the part in my answer referring to \b.