Home > Enterprise >  take all lines between two pattern by Regex
take all lines between two pattern by Regex

Time:10-05

I used

(?<=<li>)..(?=</li>)
for only ONE LINE like this:
pattern1 Everything pattern2
but it not work for multiple lines!
how can take everything and all lines(1,2,3,4,5) from like this:
(spaces are't necessary)

<pre>
pattern1
line1
   line2
      line3
   line4
line5
pattern2
</pre>

CodePudding user response:

For many lines you may need option re.DOTALL and/or re.MULTILINE

text = '''<pre>
pattern1
line1
   line2
      line3
   line4
line5
pattern2
</pre>'''

import re

result = re.findall('pattern1(.*)pattern2', text, re.DOTALL)

print('len:', len(result))
print(result[0].strip())

Result:

len: 1

line1
   line2
      line3
   line4
line5
  • Related