Reputation: 217
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("^{}$".format(word),line):
return True
return False
if find_string('/tmp/myfile', 'hello'):
print("found")
else:
print("not found")
myfile:
hello world #does not match
hello #match
If I remove ^ and $ then it will match but it will also match "he","hel" etc. How can I match the exact string if there are multiples words on a single line?
Upvotes: 1
Views: 4770
Reputation:
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.
Upvotes: 1
Reputation: 70
Do you want something like this? Sorry if not
import re
with open('regex.txt', 'r') as a:
word = "hello"
for line in a:
line = line.rstrip()
if re.search(r"({})".format(word), line):
print(f'{line} ->>>> match!')
else:
print(f'{line} ->>>> not match!')
text file:
hello world #does not match
hello #match
test here
teste hello here
[output]
hello world #does not match ->>>> match!
hello #match ->>>> match!
test here ->>>> not match!
teste hello here ->>>> match!
Upvotes: 0