I am trying to extract all of the text between two keywords in a text file. The keywords appear multiple times in the file, so I will have multiple blocks of good text.
The input.txt file is this:
bad bad keyword1 GOOD DATA keyword2 bad
bad bad bad keyword1 MORE
GOOD DATA keyword2 bad bad
This is not working:
import re
f = open('input.txt', 'r')
trim = re.findall('keyword1(.+?)keyword2', f.read())
print trim
It returns an empty list:
[]
If you want to grab all the data you should use re.DOTALL flag:
trim = re.findall('keyword1(.+?)keyword2', f.read(), re.DOTALL)
Usually the dot character means to get all chars but \n. With the DOTALL attribute the engine also matches \n for the dot character.
Output:
[' GOOD DATA ', ' MORE \nGOOD DATA ']
import re
s = "bad bad keyword1 GOOD DATA " \
"keyword2 bad bad bad bad " \
"keyword1 MORE GOOD DATA " \
"keyword2 bad bad"
for i in re.findall('keyword1(.*?)keyword2', s, re.DOTALL):
print(i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With