import re
s = '''Aug 23, 2011 10:31:35 AM This is the start of the text.
This is more Text.
This is another line
This is another line
This is more.
Aug 23, 2011 10:41:00 AM This is the next in the series.
This is another line
This is more Text.
This is another line
This is another line
This is more.
Aug 24, 2011 10:41:00 AM This is the next in the series.
This is another line
This is more Text.
This is another line
This is another line
This is more. '''
months = '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'
ch = '%s \d\d?, \d{4} \d\d:\d\d:\d\d (?:AM|am|PM|pm)' % months
regx = re.compile('%s.*?(?=%s|\Z)' % (ch,ch), re.DOTALL)
for x in regx.findall(s):
print repr(x)
print
результат
'Aug 23, 2011 10:31:35 AM This is the start of the text.\n This is more Text.\nThis is another line\nThis is another line\n This is more.\n'
'Aug 23, 2011 10:41:00 AM This is the next in the series.\nThis is another line\n This is more Text.\nThis is another line\n This is another line\n This is more.\n'
'Aug 24, 2011 10:41:00 AM This is the next in the series.\nThis is another line\n This is more Text.\nThis is another line\n This is another line\n This is more. '
Да, вам необходимо изучить инструмент регулярных выражений (модуль re
)
обновление: минимум объяснений:
parens (...)
определяют группу
без ?:
, это группа захвата
(?:......)
является группой без захвата
(?=....)
означает ** после этой точки, тамдолжна быть частью строки, соответствующей символу после ?=
, но эта часть не фиксируется: это способ получить остановку двигателя регулярного выражения непосредственно перед этой частью, не захватывая ее;это также позволяет, и, что более важно, двигатель регулярных выражений снова совмещается с начала этой части остановки, в противном случае последняя тоже будет израсходована
re.DOTALL
для создания символа.(точка), чтобы соответствовать ВСЕМ символам, содержащим '\ n', что не имеет места без этого флага