-1

我有一个看起来像这样的字符串:

"Product DescriptionThe Signature Series treatment makes the strategy
guide a COLLECTIBLE ITEM for StarCraft II fans. Single-player CAMPAIGN
WALKTHROUGH covers all possible mission branches, including bonus
objectives throughout the campaign. Exclusive MAPS found only in the
official guide, show locations of units,..."

我虽然这样做是为了删除Product Description

description_hash[:description] = @data.at_css('.featureReview span').text[/.*\.\.\./m].delete("Product Description")

但我得到了这个:

"ThSgaSammakhagygaCOLLECTIBLEITEMfSaCafIIfa.Sgl-layCAMAIGNWALKTHROUGHvallblmbah,lgbbjvhghhamag.ExlvMASflyhffalg,hwlaf,..."

我想我只是告诉 Ruby 删除单词中的所有字母Product Description(加上空格)。但我只想删除前两个词。

这样做的正确方法是什么?

4

3 回答 3

3
text = "Product DescriptionThe Signature Series treatment makes the strategy guide a COLLECTIBLE ITEM for StarCraft II fans. Single-player CAMPAIGN WALKTHROUGH covers all possible mission branches, including bonus objectives throughout the campaign. Exclusive MAPS found only in the official guide, show locations of units,..."
text[/.*\.\.\./m].sub(/\AProduct Description/, '')
# => "The Signature Series treatment makes the strategy guide a COLLECTIBLE ITEM for StarCraft II fans. Single-player CAMPAIGN WALKTHROUGH covers all possible mission branches, including bonus objectives throughout the campaign. Exclusive MAPS found only in the official guide, show locations of units,..."
于 2013-09-01T06:40:46.317 回答
2

您也可以使用该String#sub方法。

2.0.0-p247 :011 > foo.sub("Product Description", "")

我认为这也可能取代任何连续出现的“产品描述”

编辑:falsetru 的答案在技术上是优越的,OP。你应该试试看。

于 2013-09-01T06:47:26.590 回答
1

一个非常干净的方法是:

str = "Product DescriptionThe Signature Series treatment makes the strategy guide a COLLECTIBLE ITEM for StarCraft II fans. Single-player CAMPAIGN WALKTHROUGH covers all possible mission branches, including bonus objectives throughout the campaign. Exclusive MAPS found only in the official guide, show locations of units,..."

str[/\AProduct Description(.+)/, 1] # => "The Signature Series treatment makes the strategy guide a COLLECTIBLE ITEM for StarCraft II fans. Single-player CAMPAIGN WALKTHROUGH covers all possible mission branches, including bonus objectives throughout the campaign. Exclusive MAPS found only in the official guide, show locations of units,..."

虽然您可以使用搜索和替换删除第一个“有问题的”文本,但由于您知道要忽略什么,并且想要其余的,您可以轻松跳过它并告诉 Ruby 只返回所需的文本。所以,抓住你想要的,忘记删除不需要的文本。

String 的[]方法对此非常有用。除其他外,它允许我们传递带有捕获组的正则表达式,然后仅返回捕获的文本:

str[regexp, capture] → new_str or nil
于 2013-09-01T19:46:36.853 回答