我有一堆缺少撇號的短語,我有一系列的修復,如下所示:
phrase = "i d let some"
def contractions_to_fix
[
{ missing: "let s", fixed: "let's" },
{ missing: "i d", fixed: "i'd" }
]
end
我正在嘗試遍歷收縮陣列以替換它們,如下所示:
contractions_to_fix.each do |contraction|
if phrase.include? contraction[:missing]
idea_title.gsub! contraction[:missing], contraction[:fixed]
end
end
在這個例子中,目標是回傳"i'd let some";但是,到目前為止我嘗試過的每個正則運算式都會回傳錯誤的回應。
例如:
contraction[:missing]結果是"i'd let'some/\bcontraction[:missing]\b/結果是"i d let some"
任何幫助將非常感激!
uj5u.com熱心網友回復:
在您的標題中編碼確切要求的最簡單方法是翻轉您的條件:“前面或后面沒有非空格”:
idea_title.gsub!(/(?<!\S)#{Regexp.escape(contraction[:missing])}(?!\S)/, contraction[:fixed])
雖然/\b#{...}\b/應該適用于您給出的示例。您的問題可能是您將 aString作為模式輸入gsub!而不是Regexp,因此您實際上是在尋找\b(反斜杠和小寫B),而不是單詞邊界。試試看
idea_title.gsub!(/\b#{Regexp.escape(contraction[:missing])}\b/, contraction[:fixed])
uj5u.com熱心網友回復:
arr = [
{ missing: "let s", fixed: "let's" },
{ missing: "i d", fixed: "i'd" }
]
h = arr.reduce({}) { |h,g| h.merge(g[:missing]=>g[:fixed]) }
#=> {"let s"=>"let's", "i d"=>"i'd"}
r = /\b(?:#{h.keys.join('|')})\b/
#=> /\b(?:let s|i d)\b/
"i d want to let some".gsub(r, h)
#=> "i'd want to let some"
這使用String.gsub的(第二種)形式,它將散列作為第二個引數并且沒有塊。
可以替代地計算h如下。
h = arr.map { |g| g.values_at(:missing, :fixed) }.to_h
#=> {"let s"=>"let's", "i d"=>"i'd"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389765.html
上一篇:ruby&postgresRuby在macOS環境中連接到資料庫錯誤
下一篇:Ruby動態更新嵌套陣列中的值
