Exact Word Match in String with Regex in Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BaseballGraphs
    New Member
    • Sep 2010
    • 75

    Exact Word Match in String with Regex in Python

    Hello,
    I've been trying to come up with a way to search for the exact match of one word (as a string) within another string.

    So, for example, if I were searching for the string, 'eligible', searching it against the string 'ineligible' would not yield a result.

    Here is the code I have thus far:
    Code:
    def findstring(string1, string2):
      if re.search(r'(^|[^a-z0-9])'+re.escape(string1)+r'($|[^a-z0-9])', string2):
        return True
      return False
    This, however, still would match 'ineligible.' What is the regex needed to ensure that only exact words are matched?

    Thank you for your help!
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You can use the \b word boundaries to make sure it's an exact word match.

    Comment

    Working...