如果我得到你的問題的權利,你要n
後刪除所有哈希標籤的話你可以像這樣做:
str = "The mountains of #Chamonix France are famous for skiing, alpine climbing, base-jumping, #Paragliding, raw adventure and #Home of the first Winter Olympics. It's an adventurers and photographers paradise. Seen here, a long exposure of the #Druis, one of many striking"
n = 2
str.gsub(/#{str.scan(/#\w+/)[n..-1].join('|')}/,'')
# => "The mountains of #Chamonix France are famous for skiing, alpine climbing, base-jumping, #Paragliding, raw adventure and of the first Winter Olympics. It's an adventurers and photographers paradise. Seen here, a long exposure of the , one of many striking"
說明:
首先我們得到了所有的哈希標籤的話:
str.scan(/#\w+/)
# => ["#Chamonix", "#Paragliding", "#Home", "#Druis"]
現在我們關心的第二個指標後唯一的話,即
str.scan(/#\w+/)[n..-1] # n is 2
# => ["#Home", "#Druis"]
現在,讓我們創建一個正則表達式來查找字符串這些話。在這裏:
/str.scan(/#\w+/)[n..-1].join('|')/
# /#Home|#Druis/
最後用gsub
''
替換它們。保持所有的東西放在一起,我們得到:
str.gsub(/#{str.scan(/#\w+/)[n..-1].join('|')}/,'')
問題不明,請重新配製。現在,它看起來好像你想從字符串中取出數字'2',並從結尾刪除2'#...'s。 –
哪些單詞是相同的單詞? – sawa