我有一个看起来像这样的字符串:
"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
(加空格)中的所有字母。但我只想删除前两个单词。
这样做的正确方法是什么?
答案 0 :(得分: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,..."
答案 1 :(得分:2)
您还可以使用String#sub
方法。
2.0.0-p247 :011 > foo.sub("Product Description", "")
我认为也可能取代任何连续出现的“产品描述”
编辑:falsetru的答案在技术上更优越,OP。你应该尝试一下。
答案 2 :(得分: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