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

后端 未结 2 442
囚心锁ツ
囚心锁ツ 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:06
     with open(somefile, 'r') as f:
         line_numbers = [n for n, line in enumerate(f) if re.search(someRegexp, line)]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题