首页 > 解决方案 > 如何根据 R 中的条件拆分字符串?

问题描述

我想通过查看单词'split here'将单个字符串拆分为多个字符串,前提是它存在于'>'和'<'之间,并且不删除除单词'split here'之外的任何其他字符

text <- c("Don't split here > yes here split here and blah blah < again don't (anything could be here) split here >")

预期输出:

text[1] = "Don't split here > yes here "
text[2] = "and blah blah < again don't (anything could be here) split here >"

我试过了

gsub(">(.*split here.*)<","", text)

但这似乎不起作用。有人可以使用正则表达式 exp。帮帮我?

标签: rregexgsub

解决方案


用 \1 替换所需的字符串,然后在 \1 上拆分:

strsplit(gsub("(>[^<]+) split here ([^<]+<)", "\\1\1\\2", text), "\1")
## [[1]]
## [1] "Don't split here > yes here"             
## [2] "and blah blah < again don't split here >"

如果输入是字符向量,则输出将是一个列表,或者如果您想展平它,只需使用上面代码unlist(s)s的结果。


推荐阅读