[英]How do I replace words in a string based on words in an Array in Ruby?
我該怎么辦? 我嘗試過這個gsub,但是如果strings_to_highlight數組很大,我無法弄清楚它真正有效。 干杯!
string = "Roses are red, violets are blue"
strings_to_highlight = ['red', 'blue']
# ALGORITHM HERE
resulting_string = "Roses are (red), violets are (blue)"
Regexp
有一個有用的union
函數,用於將正則表達式組合在一起。 堅持使用regexp,直到遇到性能問題:
string = "Roses are red, violets are blue"
strings_to_highlight = ['red', 'blue']
def highlight(str, words)
matcher = Regexp.union words.map { |w| /\b(#{Regexp.escape(w)})\b/ }
str.gsub(matcher) { |word| "(#{word})" }
end
puts highlight(string, strings_to_highlight)
strings_to_highlight = ['red', 'blue']
string = "Roses are red, violets are blue"
strings_to_highlight.each { |i| string.gsub!(/\b#{i}\b/, "(#{i})")}
我建議使用String#gsub的形式,它使用哈希進行替換。
strings_to_highlight = ['red', 'blue']
首先構造哈希。
h = strings_to_highlight.each_with_object({}) do |s,h|
h[s] = "(#{s})"
ss = "#{s[0].swapcase}#{s[1..-1]}"
h[ss] = "(#{ss})"
end
#=> {"red"=>"(red)", "Red"=>"(Red)", "Blue"=>"(Blue)", "blue"=>"(blue)"}
接下來為它定義一個默認的proc:
h.default_proc = ->(h,k) { k }
因此,如果h
沒有密鑰k
,則h[k]
返回k
(例如, h["cat"] #=> "cat"
)。
准備好出發!
string = "Roses are Red, violets are blue"
string.gsub(/[[[:alpha:]]]+/, h)
=> "Roses are (Red), violets are (blue)"
這應該是相對有效的,因為只需要通過字符串一次並且哈希查找非常快。
我用的是:
string = "Roses are red, violets are blue"
strings_to_highlight = ['red', 'blue']
string.gsub(/\b(#{Regexp.union(strings_to_highlight).source})\b/) { |s| "(#{s})" } # => "Roses are (red), violets are (blue)"
以下是它如何分解:
/\b(#{Regexp.union(strings_to_highlight).source})\b/ # => /\b(red|blue)\b/
嵌入模式時使用source
非常重要。 沒有它會導致:
/\b(#{Regexp.union(strings_to_highlight)})\b/ # => /\b((?-mix:red|blue))\b/
如果您不理解regex-ese中的含義,那么(?-mix:...)
部分可能會導致問題。 Regexp文檔解釋了這些標志,但如果你不知道這個問題,那么如果沒有這樣做就會導致很難診斷出來。
\\b
告訴引擎匹配單詞,而不是子串。 沒有它你可能最終得到:
string = "Fred, bluette"
strings_to_highlight = ['red', 'blue']
string.gsub(/(#{Regexp.union(strings_to_highlight).source})/) { |s| "(#{s})" }
# => "F(red), (blue)tte"
使用帶有gsub
的塊允許我們對匹配的值執行計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.