ruby-on-railsrubyregexruby-on-rails-3

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: XXXXXXXX\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. Why might this be the case?

split(/(From:.*Date.*To:.*Subject:.*?)\n/m).first

Solution

  • 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]