在R中每两个字符添加一个空格

时间:2017-07-31 13:47:43

标签: r regex

我的电话号码是:

0123456789

我想让它们看起来像

01 23 45 67 89

到目前为止,添加零与paste0函数没什么关系,但我想要比嵌套paste0substr的长链更简单一些。正则表达式每两位数读一次可能是可能的,但我不知道如何实现它。

3 个答案:

答案 0 :(得分:1)

您可以使用(.{2})替换正则表达式\\1。请注意,还存在尾随空白问题,因为我们不希望在字符串末尾添加额外的空间用于具有偶数位数的输入。为了解决这个问题,我们可以从替换后的字符串中删除尾随空格。

x <- '0123456789'
y <- sub("\\s+$", "", gsub('(.{2})', '\\1 ', x))
y
[1] "01 23 45 67 89"

Demo

答案 1 :(得分:0)

这是一个比蒂姆更重要的解决方案,但你可以用dplyrstringr来做这样的事情

library(dplyr)
library(stringr)
original_string %>% 
  paste0(0, .) %>% # add 0 to the head
  str_replace_all("(.{2})", "\\1 ") %>% # insert spaces after every to digits
  str_trim() # remove the space in the end if it's there

答案 2 :(得分:0)

没有正则表达式:

x <- "0123456789"
formatC(as.numeric(x), big.mark = " ", big.interval = 2, 
        format = "d", flag = "0", width = nchar(x))
#[1] "01 23 45 67 89"
相关问题