在R中减去一个字符串

时间:2016-08-08 09:00:11

标签: r

我有一个这样的字符串:

phrase <- "this_is.//the_first?the_second"

因此我想基于这个字符串减去?并将此作为结果

>phrase_new[1]
 "this_is.//the_first?"
>phrase_new[2]
  "the_second"

我试试这个但是没有用。请问有什么想法吗?

phrase_new <- sub("[:?:]", "", phrase)

3 个答案:

答案 0 :(得分:3)

如果您想按字符拆分,请更好地使用docs

> strsplit(phrase, "?", fixed = TRUE)
[[1]]
[1] "this_is.//the_first" "the_second"

答案 1 :(得分:2)

如果我们需要sub,我们可以捕获字符,直到?作为一个组((...)),在替换中,我们提供反向引用(\\1)对于那个小组。

sub("(.*\\?).*", "\\1", phrase)
#[1] "this_is.//the_first?"

对于第二个子字符串,我们将一个或多个字符(.*)与?匹配,并将其替换为""

sub(".*\\?", "", phrase)
#[1] "the_second"

答案 2 :(得分:1)

正如@ m0nhawk所建议的那样,strsplit非常适合打破字符串。但是,对于您要求提取元素,您必须使用双方括号

phrase <- "this_is.//the_first?the_second"
phrase_new <- strsplit(phrase,split = '?',fixed = T)[[1]]
phrase_new[1]
phrase_new[2]
相关问题