Return all lines following a matched date and time up, but not including the next date and time?
I'm trying to grab a snippet of text from a file that exists between two lines. Specifically I need to be able to grab a line and all the following lines up until another specific line.
For example, the Raw file would contain something like this:
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 开发者_JAVA技巧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.
And I need it to parse through and return:
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.
Does anyone have any suggestions on the method to implement this?
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
result
'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. '
Yes, you'll have to learn the regex tool (module re
)
update: a minimum of explanations:
parens (...)
define a group
without ?:
, it is a capturing group
(?:......)
is a non capturing group
(?=....)
means **after this point, there must be a portion of string matching what is symbolised after ?=
, but this portion isn't captured: that's the way to obtain a stop of the regex motor just before this portion, without capturing it; that allows too, and it is the more important, the regex motor to match again from the beginning of this stopping portion, otehrwise the latter would be consumed too
re.DOTALL
is to make the symbol . (the dot) to match ALL the characters, comprised '\n' , which is not the case without this flag
精彩评论