在字符串中的特定位置插入 space

Inserting space at specific location in a string

我想在字符串中的三个字符后添加白色 space。我使用了以下代码,效果很好。我想知道是否有任何其他简单的方法可以完成同样的任务

library(stringi)
Test <- "3061660217"
paste(
    stri_sub(str = Test, from = 1, to = 3)
  , stri_sub(str = Test, from = 4)
  , sep = " "
  )

[1] "306 1660217"

使用基本的 regexstringr:

library(stringr)
str_replace(Test, pattern = "(.{3})(.*)", replacement = "\1 \2")

输出:

"306 1660217"

同样的方法也适用于基础R

gsub(Test, pattern = "(.{3})(.*)", replacement = "\1 \2")

解释:

  1. (.{3}) - 找到任意 3 个字符
  2. (.*) - 找到任何字符 0 次或更多次
  3. \1 - 反向引用 (.{3})
  4. \2 - 反向引用 (.*)
  5. \1\2之间的space就是你要添加的space