【问题标题】:Python search for an exact string in a filePython 在文件中搜索精确的字符串
【发布时间】:2020-06-17 16:05:09
【问题描述】:
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")

我的文件:

hello world #does not match
hello #match

如果我删除 ^ 和 $ 那么它会匹配,但它也会匹配 "he","hel" 等。如果单行上有多个单词,我如何匹配确切的字符串?

【问题讨论】:

  • 你能扩展你想要匹配的内容吗?如果您想匹配正好是word 的行,那么line.rstrip() == word 就可以了。
  • 使用单词边界\bhello\b。请看demo
  • 这很好。您是否要匹配一行中的单个单词?如果您只是想在“hello world”中匹配字符串“hel”,那么它就在那里。这是一个适当的匹配。
  • 尝试:if re.search(r"\b{}\b".format(word),line): 并注意正则表达式字符串之前的r,以确保正确解释反斜杠。
  • 如果您不回答问题,我们无法解决此问题。

标签: python regex search


【解决方案1】:

您可以尝试在文本周围使用word-boundaries。比如:

\bhello\b

你可以在here.找到上述正则表达式的demo

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")

您可以在here.中找到上述实现的示例运行

【讨论】:

    【解决方案2】:

    你想要这样的东西吗?不然很抱歉

    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!
    

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多