r - 如何根据 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。帮帮我?
解决方案
用 \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
的结果。
推荐阅读
- node.js - HTTP 错误 500.1013 Azure 应用服务节点 8.9.4
- puppeteer - Puppeteer:如何导航到从 $$ 获得的元素?
- sql - 阿拉伯字符串Oracle数据库上的WHERE子句匹配问题
- javascript - 根据元素的频率对数组进行排序
- html - CSS - 粘性网格标题
- regex - 查找具有 2 个或更多 * 的字符
- java - Gradle 多模块 jar 升级问题
- python - 如何从深度差异中完全排除“type_changes”,因为我只关心值的变化?
- react-native - 在 Speech to Text 中识别多个用户(React Native)
- django - DJango 查询外键优化