2013-09-01 66 views
-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(加空格)中的所有字母。但我只想刪除前兩個單詞。

這樣做的正確方法是什麼?

+0

-1對於寫作'description_hash。[:描述] = @ data.at_css(」 featureReview跨度').text'沒有任何解釋。究竟是什麼並不清楚。也許,這部分與問題無關,因此不應該寫在問題中。 – sawa

回答

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,..." 
+0

爲什麼不只是'text.gsub(「Product Description」,「」)'? –

+0

@AmitKumarGupta,不要意外刪除中間的產品描述。 – falsetru

+3

@falsetru,Amit Kumar Gupta,你爲什麼要提示'gsub'?是不是更合適?而爲了這個目的,最好使用'\ A'而不是'^'。 – sawa

2

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

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

,我認爲也可以代替「產品說明」的任何連續出現次數

編輯:falsetru的答案是技術上的優勢,OP。你應該嘗試一下。

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 
相關問題