r - 删除字符串中位置标识的某个事件之前的所有内容
问题描述
我有一个看起来像的字符串a
。
我想删除从第二次到最后一次出现模式之前的所有内容=== test
,===
包括在内。
a <- "=== test : {abc}
=== test : {abc}
=== test : {abc}
=== test : {aUs*}
=== dce
=== test : {12abc}
=== abc
=== test : {abc}
=== test : {dfg}"
result <- "test : {abc}
=== test : {dfg}"
我试过了:
gsub(".*=== test", "", a)
如何将索引设置为第二个?
谢谢
解决方案
下面应该工作。我将数据拆分为一个由换行符分隔的向量\\n
(额外的反斜杠是为了“转义”特殊字符),然后用于grep
查找模式^=== test
的所有出现,前导^
意味着字符串应该以此开头。
数据
a <- "=== test : {abc}
=== test : {abc}
=== test : {abc}
=== test : {aUs*}
=== dce
=== test : {12abc}
=== abc
=== test : {abc}
=== test : {dfg}"
代码
# convert to a vector for ease
b <- unlist(strsplit(a, '\\n'))
# get indices for each occurrence of the pattern
indices <- grep('^=== test', b)
# we only need the last two occurrences
n <- length(indices)
res <- b[indices[(n-1):n]]
# res is a vector with two entries, to get it back to a single entry
# same as the original data, we use paste(.., collapse = '\\n')
result <- paste(res, collapse = '\\n')
输出
> result
[1] "=== test : {abc}\\n=== test : {dfg}"
推荐阅读
- c - 如何关闭在外部函数中打开的文件
- node.js - 检查当前用户是否登录
- android - 在 RecyclerView 上更改 CardBackgroundColor
- r - R Markdown 到表格的内部链接
- c# - 先前工作代码中与填充相关的 CryptographicException
- node.js - 如何在 Nodejs 中使用 curl
- unity3d - 为什么我的所有场景都在启动时加载?(统一)
- c# - Vuzix Blade 上的 Firebase(Unity SDK):OnTokenReceived 从未触发
- rest - 泽西岛的稀疏查询
- python - 我在 React 中编写 axios post 方法并添加 Access-Control-Allow-Origin 但请求不起作用并响应我 cors origin 错误