我认为在 R 中提取多个捕获组基本上有三种简单的方法(不使用替换); str_match_all、str_extract_all 和 regmatches/gregexpr 组合。
我喜欢@kohske 的正则表达式,它在后面寻找一个左括号?<=\\(,在前面寻找一个右括号?=\\),并抓住中间的所有东西(懒惰地).+?,换句话说(?<=\\().+?(?=\\))
使用相同的正则表达式:
str_match_all 将答案作为矩阵返回。
str_match_all(j, "(?<=\\().+?(?=\\))")
[,1]
[1,] "wonder"
[2,] "groan"
[3,] "Laugh"
# Subset the matrix like this....
str_match_all(j, "(?<=\\().+?(?=\\))")[[1]][,1]
[1] "wonder" "groan" "Laugh"
str_extract_all 以列表的形式返回答案。
str_extract_all(j, "(?<=\\().+?(?=\\))")
[[1]]
[1] "wonder" "groan" "Laugh"
#Subset the list...
str_extract_all(j, "(?<=\\().+?(?=\\))")[[1]]
[1] "wonder" "groan" "Laugh"
regmatches/gregexpr 还将答案作为列表返回。由于这是基本 R 选项,因此有些人更喜欢它。注意推荐的perl = TRUE。
regmatches(j, gregexpr( "(?<=\\().+?(?=\\))", j, perl = T))
[[1]]
[1] "wonder" "groan" "Laugh"
#Subset the list...
regmatches(j, gregexpr( "(?<=\\().+?(?=\\))", j, perl = T))[[1]]
[1] "wonder" "groan" "Laugh"
如果我错误地描述了最受欢迎的选项,希望 SO 社区能够更正/编辑此答案。