Extract Values between two strings in a text file

后端 未结 5 393
旧巷少年郎
旧巷少年郎 2021-01-22 15:56

Lets say I have a Text file with the below content

fdsjhgjhg
fdshkjhk
 Start
     Good Morning
     Hello World
 End
dashjkhjk
dsfjkhk
Start
  hgjkkl
  dfghjjk
          


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 16:07

    You can do this with regular expressions. This will exclude rogue Start and End lines. Here is a live example

    import re
    
    f = open('test.txt','r')
    txt = f.read()
    matches = re.findall(r'^\s*Start\s*$\n((?:^\s*(?!Start).*$\n)*?)^\s*End\s*$', txt, flags=re.M)
    

提交回复
热议问题