根据R

时间:2017-06-09 19:11:38

标签: r split strsplit

我有以下字符串和向量:

temp = "EarthMars Venus & Saturn PlanetsJupiter"

searchTerms = c("Earth", "Jupiter", "Mars", "Venus & Saturn Planets", "Neptune")

我想根据'searchTerms'中的字符串拆分'temp',以便我得到以下内容:

result = c("Earth", "Mars", "Venus & Saturn Planets", "Jupiter") 

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

使用stringr包,您可以执行以下操作:

library(stringr)
result = unlist(str_extract_all(temp,searchTerms))

[1] "Earth"          "Jupiter"         "Mars"           "Venus & Saturn Planets"

答案 1 :(得分:1)

与此帖子(R split on delimiter (split) keep the delimiter (split))类似的一个选项是:

searchStr <- paste0(searchTerms, collapse = "|")
unlist(strsplit(temp, paste0("(?<=",searchStr,")"), perl = T))

[1] "Earth" "Mars"  " Venus & Saturn Planets" "Jupiter"   

答案 2 :(得分:1)

另一个只有基本功能的单线选项:

result <- unlist(lapply(searchTerms, function(x) regmatches(temp,regexpr(x,temp))))