且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用 R 中的相应替换字符串替换一组模式匹配

更新时间:2022-11-14 14:24:08

使用 PCRE 而不是固定匹配在我的机器上花费了大约 1/3 的时间.

Using PCRE instead of fixed matching takes ~1/3 the time on my machine for your example.

xxx_replace_xxx_pcre <- function(string, patterns, replacements) {
   for (i in seq_along(patterns))
      string <- gsub(patterns[i], replacements[i], string, perl=TRUE)
   string
}
system.time(x <- xxx_replace_xxx(string, patterns, replacements))
#    user  system elapsed 
#   0.491   0.000   0.491 
system.time(p <- xxx_replace_xxx_pcre(string, patterns, replacements))
#    user  system elapsed 
#   0.162   0.000   0.162 
identical(x,p)
# [1] TRUE