How to get line numbers of the snippets matching a regexp?

后端 未结 2 432
囚心锁ツ
囚心锁ツ 2021-01-23 00:37

How is it possible to obtain the line numbers of all the text snippets matching a given regexp, within a file?

file_content = f.rea         


        
2条回答
  •  囚心锁ツ
    2021-01-23 01:09

    import re
    reg="ha*"
    count=0
    f = open(somefile,'r')
    while True:
            line= f.readline()
            if not line: break
            else:
                    count+=1
                    if re.search(reg,line):
                            print count,line
    

提交回复
热议问题