[英]Fastest way to search and replace in a string in Ruby?
我正在構建一個庫,用於清理用戶生成的內容並進行數以千計的字符串替換(性能是關鍵)。
在字符串中進行搜索和替換的最快方法是什么?
這是庫將進行的替換的示例:
u2 => you too
2day => today
2moro => tomorrow
2morrow => tomorrow
2tomorow => tomorrow
關於字符串如何出現有四種情況:
2day sample
sample 2day sample
sample 2day
2day
即,如果正則表達式位於sample2daysample
之類的單詞中間,則不應替換它
可能的解決方案:
replaces = {'u2' => 'you too', '2day' => 'today', '2moro' => 'tomorrow'}
str = '2day and 2moro are u2 sample2daysample'
#exp = Regexp.union(replaces.keys) #it is the best but to use \b this should be a quiet different
exp = Regexp.new(replaces.keys.map { |x| "\\b" + Regexp.escape(x) + "\\b" }.join('|'))
str = str.gsub(exp, replaces)
# => "today and tomorrow are you too sample2daysample"
完全披露:我是這個寶石的作者
如果您不需要正則表達式,可以嘗試使用https://github.com/jedld/multi_string_replace這使用 aho-corasick 算法來實現此目的。
user system total real
multi gsub 1.322510 0.000000 1.322510 ( 1.344405)
MultiStringReplace 0.196823 0.007979 0.204802 ( 0.207219)
mreplace 0.200593 0.004031 0.204624 ( 0.205379)
我看到的唯一問題是該算法不理解單詞邊界,因此您必須將用例分解為:
“2天”,“2天”,“2天”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.