如何在文件中搜索字符串

时间:2016-02-29 10:20:24

标签: python regex

我必须在文件中搜索s="xyz-123."s来自其他一些代码

import re
s="xyz-123."  # This will come from some other code

f=open("\path","r")
searched_item = re.findall(r's[-]+?[0-9a-zA-Z-]+[-]+[a-zA-Z0-9]+[.]+[a-zA-Z0-9]+[.]+[a-zA-Z0-9]+', f.read())

1 个答案:

答案 0 :(得分:1)

如果s是固定字符串,那么在字符串中使用find而不是涉及regex

会更简单
def findall(p, s):
    '''Yields all the positions of
    the pattern p in the string s.'''
    i = s.find(p)
    while i != -1:
        yield i
        i = s.find(p, i+1)

import re
s="xyz-123."  # This will come from some other code
f=open("\path","r")
file_content = f.read()
for match_index in findall(s, file_content):
    print match_index