簡體   English   中英

在 Ruby 中的正則表達式匹配之前插入字符串的好方法

[英]A good way to insert a string before a regex match in Ruby

有什么好方法可以做到這一點? 似乎我可以使用幾種不同方法的組合來實現我想要的,但我可能忽略了一種更簡單的方法。 例如,PHP function preg_replace 將執行此操作。 Ruby 有什么類似的嗎?

我打算做的簡單例子:

orig_string = "all dogs go to heaven"
string_to_insert = "nice "
regex = /dogs/

end_result = "all nice dogs go to heaven"

可以使用 Ruby 的“gsub”來完成,如下所示:

http://railsforphp.com/2008/01/17/regular-expressions-in-ruby/#preg_replace

orig_string = "all dogs go to heaven"
end_result = orig_string.gsub(/dogs/, 'nice \0')
result = subject.gsub(/(?=\bdogs\b)/, 'nice ')

正則表達式檢查字符串中的每個 position 是否可以匹配整個單詞dogs ,然后將字符串nice插入那里。

單詞邊界錨\b確保我們不會意外匹配hotdogs等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM