You can use the word-boundaries of regular expressions. Example:

import re

s = '98787This is correct'
for words in ['This is correct', 'This', 'is', 'correct']:
    if re.search(r'\b' + words + r'\b', s):
        print('{0} found'.format(words))

That yields:

is found
correct found

For an exact match, replace \b assertions with ^ and $ to restrict the match to the begin and end of line.

Answer from Birei on Stack Overflow
🌐
Note.nkmk.me
note.nkmk.me › home › python
String Comparison in Python (Exact/Partial Match, etc.) | note.nkmk.me
April 29, 2025 - Uppercase and lowercase strings ... allow for more flexible string comparisons. ... Use re.search() to find a match anywhere in the string, including partial matches....
Discussions

python - finding an exact match for string - Stack Overflow
I used the following function to find the exact match for words in a string. More on stackoverflow.com
🌐 stackoverflow.com
python - Find exact match in list of strings - Stack Overflow
@pushkin, Partial matches means if you have a list a = ['FOO', 'FOOL', 'A', 'B'] and looking for only string FOO in the list, your code appends both FOO and FOOL to the matches list, which means your code append both exact match ('FOO') and partial match ('FOOL') and the question is 'Find exact ... More on stackoverflow.com
🌐 stackoverflow.com
How to use str.contains to get exact matches and not partial ones?
If you're looking for exact matches, str.contains may not be the function you should be using. The output looks correct to me in that all of the strings in the output do contain your keyword. More on reddit.com
🌐 r/learnpython
11
2
November 10, 2021
loops - Python string search: how to find exact matches, and not match with strings that contain searched string in them - Stack Overflow
I need my script to bring up definitions for different words. I'm using a loop to look for matches between between an item in a string (X) and and array. if any(i in X for i in ('coconut, Coconu... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › how can i find all exact occurrences of a string, or close matches of it, in a longer string in python?
r/learnpython on Reddit: How can I find all exact occurrences of a string, or close matches of it, in a longer string in Python?
May 9, 2024 -

Goal:

  • I'd like to find all exact occurrences of a string, or close matches of it, in a longer string in Python.

  • I'd also like to know the location of these occurrences in the longer string.

  • To define what a close match is, I'd like to set a threshold, e.g. number of edits if using the edit distance as the metric.

  • I'd also like the code to give a matching score (the one that is likely used to determine if a candidate substring is over the matching threshold I set).

How can I do so in Python?


Example:

long_string = """1. Bob likes classical music very much.
2. This is classic music!
3. This is a classic musical. It has a lot of classical musics.
"""

query_string = "classical music"

I'd like the Python code to find "classical music" and possibly "classic music", "classic musical" and "classical musics" depending on the string matching threshold I set.


Research: I found Checking fuzzy/approximate substring existing in a longer string, in Python? but the question focuses on the best match only (i.e., not all occurrences) and answers either also focuses on the best match or don't work on multi-word query strings (since the question only had a single-word query strings, or return some incorrect score (doesn't get a perfect score even for an exact match).

🌐
Quora
quora.com › How-do-you-use-a-Python-regular-expression-to-find-an-exact-string-match
How to use a Python regular expression to find an exact string match - Quora
Answer (1 of 3): First of all, I should mention that Regular Expressions is extremely versatile. Whilst it can be used in this application, a normal search algorithm can do it fine. For this case; [code]paragraphs = re.findall(r' (.*?) ', str(respData)) # . = Any Character except fo...
🌐
Finxter
blog.finxter.com › home › learn python blog › how to match an exact word in python regex? (answer: don’t)
How to Match an Exact Word in Python Regex? (Answer: Don't) - Be on the Right Side of Change
May 31, 2022 - You can use the word boundary metacharacter '\b' to match only whole words. You can match case-insensitive by using the flags argument re.IGNORECASE. You can match not only one but all occurrences of a word in a string by using the re.findall() or re.finditer() methods.
Top answer
1 of 2
7

Make your own word-boundary:

def exact_Match(phrase, word):
    b = r'(\s|^|$)' 
    res = re.match(b + word + b, phrase, flags=re.IGNORECASE)
    return bool(res)

copy-paste from here to my interpreter:

>>> str1 = "award-winning blueberries"
>>> word1 = "award"
>>> word2 = "award-winning"
>>> exact_Match(str1, word1)
False
>>> exact_Match(str1, word2)
True

Actually, the casting to bool is unnecessary and not helping at all. The function is better off without it:

def exact_Match(phrase, word):
    b = r'(\s|^|$)' 
    return re.match(b + word + b, phrase, flags=re.IGNORECASE)

note: exact_Match is pretty unconventional casing. just call it exact_match.

2 of 2
2

The problem with your initial method is that '\\b' does not denote the zero-width assertion search that your looking for. (And if it did, I would use r'\b' instead because backslashes can become a real hassle in regular expressions - see this link)

From Regular Expression HOWTO

\b

Word boundary. This is a zero-width assertion that matches only at the beginning or end of a word. A word is defined as a sequence of alphanumeric characters, so the end of a word is indicated by whitespace or a non-alphanumeric character.

Because - is a non-alphanumeric character, your findall regular expression will find award in award-wining but not in awards.

Depending on your searched phrase, I would also think of using re.findall instead of re.match as suggested by Elazar. In your example re.match works, but if the word you are looking for is nested anywhere beyond the beginning of the string, re.match will not succeed.

Find elsewhere
🌐
AskPython
askpython.com › python › examples › matching-strings-using-regular-expressions
Matching Entire Strings in Python using Regular Expressions - AskPython
February 27, 2023 - To match an exact string, you can use the () grouping operator to create a capturing group around the string, and then use a backreference to match the exact same string again. For example we have a text file given below: This is a sample text file.
🌐
ZetCode
zetcode.com › python › regularexpressions
Python regular expressions - using regular expressions in Python
In the example, we look for an exact match for the 'book' term. ... A character class defines a set of characters, any one of which can occur in an input string for a match to succeed. ... #!/usr/bin/python import re words = ('a gray bird', 'grey hair', 'great look') pattern = re.compile(r'gr[ea]y') for word in words: if re.search(pattern, word): print(f'{word} matches')
🌐
Reddit
reddit.com › r/learnpython › how to use str.contains to get exact matches and not partial ones?
r/learnpython on Reddit: How to use str.contains to get exact matches and not partial ones?
November 10, 2021 -

Hi, I don't get why when I use str.contains to get exact matches from a list of keywords, the output still contains partial matches. Here is an extract of what I have (I'm only including one keyword in the list for the example):

keyword= ['SE.TER.ENRL']

subset = df[df['Code'].str.contains('|'.join(keyword), case=False, na=False)]

Output: ['SE.TER.ENRL' 'SE.TER.ENRL.FE' 'SE.TER.ENRL.FE.ZS']

Does anyone know how to get around this?

Thanks!

🌐
Parallax
learn.parallax.com › tutorials › robot › cyberbot › strings-characters-primer › compare-find-check › your-turn-exact-match-vs-found
Your Turn: Exact Match vs Found in String | LEARN.PARALLAX.COM
Sometimes a script has to make ... that there aren't more characters following the match. One way to solve this is to use the is equal to == operator to check if the string is an exact match....
🌐
Stack Overflow
stackoverflow.com › questions › 60640225 › python-string-search-how-to-find-exact-matches-and-not-match-with-strings-that
loops - Python string search: how to find exact matches, and not match with strings that contain searched string in them - Stack Overflow
Although, based on the in test, I wonder if the OP is treating/expecting X to be a list - such a test would be an illogical dictionary lookup if X were a string. 2020-03-11T16:38:27.89Z+00:00 ... Thanks everyone, I've figured it out. In this case, it was enough simply to add a space before the shorter keyword. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... New site design and philosophy for Stack Overflow: Starting February 24, 2026... ... How exactly are spiritual rulers and authorities "disarmed" by Jesus cancelling our debt on the cross?
🌐
PyTutorial
pytutorial.com › check-exact-match-substring-in-python-string
PyTutorial | Check Exact Match Substring in Python String
February 9, 2025 - Checking for an exact match substring in Python is straightforward. You can use the in operator, the find() method, or regular expressions. Each method has its use cases, so choose the one that best fits your needs.