Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

ruby - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.*?)
/m)[1]
=> "From: [email protected]
Date: 01-01-2011
To: [email protected]
Subject: This is the subject line"

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...