鉴于此:
Come Find me please. This is paragraph one.\n\nThis is paragraph two.
Capture everything before me as this is the last sentence.\n\n\n\n
From: XXX XXX <[email protected]>\nDate: Mon, 17 May 2010 10:59:40 -0700\n
To: \"xxx, xxx\" <[email protected]>\nSubject: Re: XXXXXXXX\n\ndone
Lots of other junk here
我想要回来的是:
Come Find me please. This is paragraph one.\n\nThis is paragraph two.
Capture everything before me as this is the last sentence.
我正在使用以下正则表达式,它在 rubular 上运行良好,但在 Rails 上失败。为什么会出现这种情况?
split(/(From:.*Date.*To:.*Subject:.*?)\n/m).first
根据我的测试,您的代码可以正常工作,只是它后面带有一些
"\n"
。如果您想删除它们,请在开头添加 \n*
。我不知道为什么你有括号,最后一个?
和\n
。我把它们脱下来了。
your_string.split(/\n*From:.*Date.*To:.*Subject:.*/m).first
也许使用
sub
更自然。
your_string.sub(/\n*From:.*Date.*To:.*Subject:.*/m, '')
你也可以这样做:
your_string[/.*?(?=\n*From:.*Date.*To:.*Subject:.*)/m]
如果想提取之前的所有内容,请尝试此解决方案
From:
txt.gsub(/From:.*$/m, '')
/m
选项使.
匹配换行符。
如果“From:”一词是唯一的,
>> s
=> "Come Find me please. This is paragraph one.\n\nThis is paragraph two. \nCapture everything before me as this is the last sentence.\n\n\n\n\nFrom: XXX XXX <[email protected]>\nDate: Mon, 17 May 2010 10:59:40 -0700\n\nTo: \"xxx, xxx\" <[email protected]>\nSubject: Re: XXXXXXXX\n\ndone"
>> s.split(/From:\s+/).first.strip
=> "Come Find me please. This is paragraph one.\n\nThis is paragraph two. \nCapture everything before me as this is the last sentence."