使用R中的正则表达式将所有匹配项提取到新列中

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

在我的数据中,有一列打开的文本字段数据类似于以下示例:

d <- tribble(
  ~x,
  "i am 10 and she is 50",
  "he is 32 and i am 22",
  "he may be 70 and she may be 99",
)

我想使用regex将所有两位数字提取到新列y中。我有以下代码,在提取第一个匹配项时效果很好:

d %>%
  mutate(y = str_extract(x, "([0-9]{2})"))

# A tibble: 3 x 2
  x                              y    
  <chr>                          <chr>
1 i am 10 and she is 50          10   
2 he is 32 and i am 22           32   
3 he may be 70 and she may be 99 70 

但是,是否可以使用某些标准分隔符(例如逗号)将两个两位数字都提取到同一列中?

r regex dplyr stringr mutate
1个回答
0
投票

我们可以使用str_extract_all而不是str_extract,因为str_extract仅与第一个实例匹配,因为_all后缀是全局的,并且会提取list中的所有实例,可以将它们转换回两个unnest_wider

的列
library(dplyr)
library(tidyr)
library(stringr)
d %>%  
    mutate(out =  str_extract_all(x, "\\d{2}")) %>% 
    unnest_wider(c(out))
© www.soinside.com 2019 - 2024. All rights reserved.