rubyregexrubular

Regex, how to match multiple lines?


I'm trying to match the From line all the way to the end of the Subject line in the following:

....
From: XXXXXX 
Date: Tue, 8 Mar 2011 10:52:42 -0800 
To: XXXXXXX
Subject: XXXXXXX
....

So far I have:

/From:.*Date:.*To:.*Subject/m

But that doesn't match to the end of the subject line. I tried adding $ but that had no effect.


Solution

  • You can use the /m modifier to enable multiline mode (i.e. to allow . to match newlines), and you can use ? to perform non-greedy matching:

    message = <<-MSG
    Random Line 1
    Random Line 2
    From: person@example.com
    Date: 01-01-2011
    To: friend@example.com
    Subject: This is the subject line
    Random Line 3
    Random Line 4
    MSG
    
    message.match(/(From:.*Subject.*?)\n/m)[1]
    => "From: person@example.com\nDate: 01-01-2011\nTo: friend@example.com\nSubject: This is the subject line"
    

    See http://ruby-doc.org/core/Regexp.html and search for "multiline mode" and "greedy by default".