Python: consecutive lines between matches similar to awk

后端 未结 3 664
青春惊慌失措
青春惊慌失措 2021-01-15 06:30

Given:

  • A multiline string string (already read from a file file)
  • Two patterns pattern1 and pattern2
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-15 07:05

    Use the re.DOTALL to match on anything including newlines. Then plug in the beginning pattern and end pattern:

    re.search( '[\w ]*b bb.*?d dd[ \w]*', string, re.DOTALL).group(0)
    

    Note: (1) string here is the file or string you wish to search through. (2) You'll need to import re. If you really want to be concise, perhaps to the point of fault, you can combine reading the file and extracting the pattern:

    re.search( '[\w ]*b bb.*?d dd[ \w]*', open('file').read(), re.DOTALL).group(0) 
    

提交回复
热议问题