正则表达式,如何匹配多行? [英] Regex, how to match multiple lines?
本文介绍了正则表达式,如何匹配多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将 From
行一直匹配到以下 Subject
行的末尾:
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
....
到目前为止我有:
/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.
推荐答案
您可以使用 /m
修饰符来启用多行模式(即允许 .
匹配换行符),并且可以使用 ?
进行非贪婪匹配:
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.*?)\n/m)[1]
=> "From: person@example.com\nDate: 01-01-2011\nTo: friend@example.com\nSubject: This is the subject line"
参见 http://ruby-doc.org/core/Regexp.html并搜索多行模式"和默认贪婪".
See http://ruby-doc.org/core/Regexp.html and search for "multiline mode" and "greedy by default".
这篇关于正则表达式,如何匹配多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文