Regex help, works on rubular not on production? Possible \n issue?
Given this:
Come Find me please. This is paragraph one.\n\nThis is paragraph two.
Capture everything before me as this is the last sentence.\n\n\n\n
From: XXX XXX <xxxxx@gmail.com>\nDate: Mon, 17 May 2010 10:59:40 -0700\n
To: \"xxx, xxx\" <xxxxx@intuit.com>\nSubject: Re: XXXXX开发者_运维百科XXX\n\ndone
Lots of other junk here
What I want back is:
Come Find me please. This is paragraph one.\n\nThis is paragraph two.
Capture everything before me as this is the last sentence.
I'm using the following regex which works fine on rubular but fails in rails. Ideas why?
split(/(From:.*Date.*To:.*Subject:.*?)\n/m).first
Thank you!
Your code works as far as I tested, except that it is trailed with some "\n"
. If you want to remove them, add \n*
to the beginning. I am not sure why you have the parentheses, and the last ?
and \n
. I took them off.
your_string.split(/\n*From:.*Date.*To:.*Subject:.*/m).first
Maybe using sub
is more natural.
your_string.sub(/\n*From:.*Date.*To:.*Subject:.*/m, '')
You can also do this:
your_string[/.*?(?=\n*From:.*Date.*To:.*Subject:.*)/m]
Try this solution if want to extract every thing before From:
txt.gsub(/From:.*$/m, '')
The /m
option makes the .
match newlines.
If the word "From: " is unique,
>> s
=> "Come Find me please. This is paragraph one.\n\nThis is paragraph two. \nCapture everything before me as this is the last sentence.\n\n\n\n\nFrom: XXX XXX <xxxxx@gmail.com>\nDate: Mon, 17 May 2010 10:59:40 -0700\n\nTo: \"xxx, xxx\" <xxxxx@intuit.com>\nSubject: Re: XXXXXXXX\n\ndone"
>> s.split(/From:\s+/).first.strip
=> "Come Find me please. This is paragraph one.\n\nThis is paragraph two. \nCapture everything before me as this is the last sentence."
精彩评论