Search code examples
rubyregexrubular

How to match text in between two words(a..b) till the first occurence of the ending word(b)


Can anyone help me to match the text between From and first occurrence of Subject from the following set of lines,

Input

Random Line 1
Random Line 2
From: [email protected]
Date: 01-01-2011
To: [email protected]
   Subject: This is the subject line
Random Line 3
Random Line 4
   Subject: This is subject
This is the end

Output

From: [email protected]
Date: 01-01-2011
To: [email protected]
   Subject: This is the subject line

I tried with the following regular expression,

/(From:.*(?i)Subject:.*?)\n/m

The above regexp selects till the last Subject


Solution

  • This works (see: http://rubular.com/r/Lw9rhfwVGt):

    /(From.*?Subject.*?)\n/m