R与字符串中的数字分开

问题描述 投票:0回答:2

我需要清理一些有单词和数字或只是数字的数据字符串。

下面是一个玩具样本

library(tidyverse)

c("555","Word 123", "two words 123", "three words here 123") %>%  
sub("(\\w+) (\\d*)",  "\\1|\\2", .)

结果是这样的:

[1] "555"                  "Word|123"             "two|words 123"        "three|words here 123"

但我想放置'|'在最后一组数字之前,如下所示

[1] "|555"                  "Word|123"             "two words|123"        "three words here|123"
r regex data-cleaning
2个回答
1
投票

我们可以使用sub来匹配零个或多个空格(\\s*),然后是我们作为一组((\\d))捕获的数字,并且在替换中使用|,然后是捕获组的反向引用(\\1

sub("\\s*(\\d)", "|\\1", v1)
#[1] "|555"                 "Word|123"            
#[3] "two words|123"        "three words here|123"

data

v1 <- c("555","Word 123", "two words 123", "three words here 123")

2
投票

你可以用

^(.*?)\s*(\d*)$

替换为\1|\2。见regex demo

enter image description here

在R:

sub("^(.*?)\\s*(\\d*)$", "\\1|\\2", .)

细节

  • ^ - 字符串的开头
  • (.*?) - 捕获第1组:任何0+字符,尽可能少
  • \s* - 零个或多个空格
  • (\d*) - 捕获第2组:零个或多个数字
  • $ - 字符串的结尾。
© www.soinside.com 2019 - 2024. All rights reserved.