R中的正则表达式和SharePoint名称

时间:2017-08-25 01:22:31

标签: r regex sharepoint stringr

我正在尝试从SharePoint生成的列表中提取名称。

列表中的每个项目至少包含一个名称和长度不同的数字ID。

列表的格式如下:

all_projects %>% 
  select(contact_names)

 A tibble: 116 x 1
                                                contact_names
                                                       <chr>
 1 last_name, first_name;#6903;#last_name, first_name;#36606
 2                               last_name, first_name;#8585
 3                                                       ...
 4                              last_name, first_name;#14801

使用stringr我已设法通过以下方式获取数字:

str_replace_all(string, pattern = ";#?\\d*", ";")

但结果是:

\"last_name, first_name;;last_name, first_name;\", 

哪个会好,但是对于;;。插入("")空字符串str_replace_all(string, pattern = ";#?\\d*", "")会返回:

\"last_name, first_namelast_name, first_name;\", 

理想情况下,我想将名字和姓氏分成两列。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我们可以使用separate/separate_rows

library(tidyverse)
separate_rows(df1, contact_names, sep = ";") %>%
        filter(!grepl("#\\d+", contact_names)) %>% 
        mutate(contact_names = str_replace_all(contact_names, "#", "")) %>%
        separate(contact_names, into = c("last", "first"), sep=",", remove = FALSE)
# A tibble: 4 x 3
#          contact_names      last       first
#*                 <chr>     <chr>       <chr>
#1 last_name, first_name last_name  first_name
#2 last_name, first_name last_name  first_name
#3 last_name, first_name last_name  first_name
#4 last_name, first_name last_name  first_name

数据

df1 <- tribble(
        ~contact_names,   
                     "last_name, first_name;#6903;#last_name, first_name;#36606",
                            "last_name, first_name;#8585", 
                           "last_name, first_name;#14801")