r语言 - str_extract所有语法



我需要一些帮助stringr::str_extract_all

x是我的数据帧的名称。

V1
(A_K9B,A_K9one,A_K9two,B_U10J) 
x = x %>% 
mutate(N_alph = map_chr(str_extract_all(x$V1, 'A_([A-Z][0-10])[A-Z]'), toString))
x = x %>% 
mutate(N_.1 = map_chr(str_extract_all(x$V1, 'A_([A-Z][0-10])[o][n][e]'), toString))
x = x %>% 
mutate(N_.2 = map_chr(str_extract_all(x$V1, 'A_([A-Z][0-10])[t][w][o]'), toString))

这是我当前的输出:

V1                                N_alph  N_.1     N_.2
(A_K9B,A_K9one,A_K9two,B_U10J)   A_K9B   A_K9one  A_K9two 

我对我的列N_alph很好,因为我希望它与其他两个分开。但理想情况下,如果我使用:

,我希望避免为那些后跟单词而不是一个字母的变量输入[o][n][e][t][w][o]:
x = x %>% 
mutate(N_alph = map_chr(str_extract_all(x$V1, 'A_([A-Z][0-10])[A-Z]'), toString))
x = x %>% 
mutate(N_all.words = map_chr(str_extract_all(x$V1, 'A_([A-Z][0-10])[\w+]'), toString))

输出是:

V1                                N_alph  N_all.words    
(A_K9B,A_K9one,A_K9two,B_U10J)   A_K9B   A_K9B,A_K9o,A_K9t 

期望输出为

V1                                N_alph  N_all.words    
(A_K9B,A_K9one,A_K9two,B_U10J)   A_K9B   A_K9one,A_K9two 

当您使用元字符如w、b、s等时,您不需要方括号。但如果你使用方括号比+需要在外面。此外,数字组应该是[0-9],因为我们谈论的是单个字符,而不是字符的组合。为了考虑大于9的数字,我们只需要扩展使用{}括号检查组的次数,或者简单地使用+操作符。最终结果如下所示:

x %>% 
mutate(N_all.words = str_extract_all(V1, 'A_([A-Z][0-9]{1,2})\w+'))

产生:

V1             N_all.words
1 (A_K9B,A_K9one,A_K9two,B_U10J) A_K9B, A_K9one, A_K9two

我还创建了一个我觉得更整洁的版本:

x %>% 
mutate(N_all.words = str_extract_all(V1, 'A_\w\d{1,2}\w+'))

最新更新