正则表达式帮助,适用于 rubular 而不是生产环境?可能的 问题?

问题描述 投票:0回答:3

鉴于此:

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
ruby-on-rails ruby regex ruby-on-rails-3
3个回答
1
投票

根据我的测试,您的代码可以正常工作,只是它后面带有一些

"\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]

0
投票

如果想提取之前的所有内容,请尝试此解决方案

From:

txt.gsub(/From:.*$/m, '')

/m
选项使
.
匹配换行符。


0
投票

如果“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."
© www.soinside.com 2019 - 2024. All rights reserved.