You may try using word-boundaries around your text. Something like:

\bhello\b

You can find the demo of the above regex in here.

Sample implementation in Python

import re
def find_string(file_name, word):
   with open(file_name, 'r') as a:
       for line in a:
           line = line.rstrip()
           if re.search(r"\b{}\b".format(word),line):
             return True
   return False

if find_string('myfile.txt', 'hello'):
    print("found")
else:
    print("not found")

You can find the sample run of the above implementation in here.

Answer from user7571182 on Stack Overflow
🌐
AskPython
askpython.com › home › matching entire strings in python 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.
🌐
Note.nkmk.me
note.nkmk.me › home › python
String Comparison in Python (Exact/Partial Match, etc.) | note.nkmk.me
April 29, 2025 - Search for a string in Python (Check if a substring is included/Get a substring position) Similar to numbers, the == operator checks if two strings are equal. If they are equal, True is returned; otherwise, False is returned. print('abc' == ...
🌐
Python Forum
python-forum.io › thread-28582.html
Exact Match
Hello, The first line of code is supposed to find string A180, and shift down 9 rows and grab that value. My problem is, is that I also have A180X inside this file, so It's not grabbing the correct information cause its also finding A180X. The se...
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 248808 › python-doing-exact-match-on-string
Python doing exact match on string [SOLVED] | DaniWeb
Does nobody read my posts? \b matches the word boundary. A regexp '\bnf\b' does exactly what the OP wants. We do read the original post. also re.sub('\bnf\b', '1.0', str) does not work either as 'nf' can be anywhere in the string.
🌐
Johns Hopkins University
cs.jhu.edu › ~langmea › resources › lecture_notes › 03_strings_exact_matching_v2.pdf pdf
Strings and Exact Matching Ben Langmead Department of Computer Science
Strings and Exact Matching · Ben Langmead · Department of Computer Science · Please sign guestbook (www.langmead-lab.org/teaching-materials) to tell me briefly how you are using the slides. For original Keynote · files, email me (ben.langmead@gmail.com).
🌐
Finxter
blog.finxter.com › how-to-match-an-exact-word-in-python-regex-answer-dont
How to Match an Exact Word in Python Regex? (Answer: Don’t) – Be on the Right Side of Change
To match an exact string 'hello' partially in 'hello world', use the simple regex 'hello'. However, a simpler and more Pythonic approach would be using the in keyword within membership expression 'hello' in 'hello world'.
Find elsewhere
🌐
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...
🌐
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 › In-Python-how-do-you-check-for-an-exact-string-match-while-ignoring-case-sensitivity
In Python, how do you check for an exact string match while ignoring case sensitivity? - Quora
Answer (1 of 6): A few helpful ideas. Python re is very forgiving just replace occurrences using re.sub then no need of a match before having to further process after a match. And if it finds no sub match or search it wont throw an error. If re doesn't find a sub it skips it anyways. And re.find...
🌐
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!

🌐
ZetCode
zetcode.com › python › regularexpressions
Python regular expressions - using regular expressions in Python
The fullmatch function looks an exact match. ... #!/usr/bin/python import re words = ('book', 'bookworm', 'Bible', 'bookish','cookbook', 'bookstore', 'pocketbook') pattern = re.compile(r'book') for word in words: if re.fullmatch(pattern, word): print(f'The {word} matches')
🌐
Stack Overflow
stackoverflow.com › questions › 55106518 › matching-exact-strings-in-python
Matching exact strings in python - Stack Overflow
You can remove the extra characters at the start of a string s using s.lstrip('-') before using an exact match.