如何将字符串的一部分捕获到向量中

How to capture parts of string into vector

我有以下字符串:

x <- "sim_K1000_human_compact"

如何将 1000human 以及 compact 捕获为 向量?

我试过了,但没有用:

> strsplit(base, "sim_K([0-9]+)_(\w+)_(\w+)")
[[1]]
[1] ""

您可以使用 stringr::str_match:

str_match(x, "sim_K([0-9]+)_(\w+)_(\w+)")[,-1]
# [1] "1000"    "human"   "compact"

这是一个潜在的基本解决方案:

x <- unlist(strsplit(gsub("sim_K", "", x), "_"))

我们可以使用 scansub

scan(text=sub("^[^_]+_.", "", x), what ="", quiet=TRUE, sep="_")
#[1] "1000"    "human"   "compact"