[英]Python search for an exact string in a file
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?如果我删除 ^ 和 $ 那么它会匹配但它也会匹配“he”、“hel”等。如果单行上有多个单词,我如何匹配确切的字符串?
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 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.您可以在此处找到上述实现的示例运行。
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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.