Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 312
AnApprentice Avatar asked Mar 09 '11 00:03

AnApprentice


People also ask

What is multiline in regex?

Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.

Which regex is used to perform multiline matching?

The RegExp m Modifier in JavaScript is used to perform multiline matching.

What is the regex mode modifier for multiline?

The "m" modifier specifies a multiline match. It only affects the behavior of start ^ and end $. ^ specifies a match at the start of a string.

How do you match everything including newline regex?

The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.


1 Answers

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: [email protected] Date: 01-01-2011 To: [email protected] Subject: This is the subject line Random Line 3 Random Line 4 MSG  message.match(/(From:.*Subject.*?)\n/m)[1] => "From: [email protected]\nDate: 01-01-2011\nTo: [email protected]\nSubject: This is the subject line" 

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

like image 89
Pan Thomakos Avatar answered Sep 22 '22 04:09

Pan Thomakos