Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 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 Reply

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...