rubyregexrubular

Match the text between two words (Words don't repeat in matched text)


I have the following as my Input,

Input

Random Line 1
Random Line 2
From: person1@example.com
Date: 01-01-2011
To: friend@example.com
   Subject: One
Random Line 3
Random Line 4
From: person2@example.com
   Subject: Two
Random Line 5
From: person3@example.com
   Subject: Three
This is the end

The following is my expected matched text,

Expected Output

From: person2@example.com
   Subject: Two

Note: There may be zero or multiple lines in between From: person2@example.com and Subject: Two

I tried with the regular expression,

/(From.*?Subject:\s*Two)/m

The above regex matches from the first From. Can anyone help me in matching the expected output? Thanks in advance.


Solution

  • Add .* before your regex to get only the expected two lines.

    .*(From.*?Subject:\s*Two)
    

    Because of greedy quantifier *, regex engine matches upto the last From string(ie, the one before the line which contains the string Two). Then from the string From upto the string Two is captured into a group(Non-greedy quantifier is used. so it do a shortest match).

    DEMO