By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,331 Members | 1,104 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,331 IT Pros & Developers. It's quick & easy.

Exact Word Match in String with Regex in Python

P: 75
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:
Expand|Select|Wrap|Line Numbers
  1. def findstring(string1, string2):
  2.   if re.search(r'(^|[^a-z0-9])'+re.escape(string1)+r'($|[^a-z0-9])', string2):
  3.     return True
  4.   return False
  5.  
This, however, still would match 'ineligible.' What is the regex needed to ensure that only exact words are matched?

Thank you for your help!
Mar 13 '13 #1
Share this Question
Share on Google+
1 Reply

Rabbit
Expert Mod 10K+
P: 12,441
You can use the \b word boundaries to make sure it's an exact word match.
Mar 13 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.