在 txt 文件中搜索不同的关键字 - 然后分配给变量

Search txt file for varying keyword - then assign to variable

我需要在 txt 文件中搜索 "i-0xxxyyyzzzz" 格式的关键字 - 其中 xyz 是不同的字母数字字符。 然后我想分配分配的每个匹配项。目前我可以达到:

  f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "i-0" in line:
        for l in searchlines[i:i+1]: print l,
        print

但是这会打印整行,而不仅仅是关键字。

我建议使用正则表达式:

import re

token_regex = re.compile('i\-0[0-9a-z]*')
for line in open('file.txt'): // Note: 'r' is the default
   // You might find the token several times in the line
   matches = token_regex.findall(line)
   if matches:
     print '\n'.join(matches)

我不清楚你想用火柴做什么。我的示例将每行打印一个。另外,你能有跨越两行的标记吗?