删除由字符串中的位置标识的特定事件之前的所有内容

Remove everything before a certain occurrence identified by position in string

我的字符串看起来像 a

我想删除倒数第 2 次出现的模式之前的所有内容 === 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 分隔的向量(额外的反斜杠是 "escape" 特殊字符),然后使用 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}"

我们可以使用strsplit按换行符拆分并选择最后两个元素。 paste 将它们放在一起并使用 sub 删除开头的 ===:

sub("^=== ", "", paste(tail(strsplit(a, split = "\n")[[1]], 2), collapse = "\n"))
# [1] "test : {abc}\n=== test : {dfg}"