首页 > 解决方案 > 删除字符串中位置标识的某个事件之前的所有内容

问题描述

我有一个看起来像的字符串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)

如何将索引设置为第二个?

谢谢

标签: rregexstringstringi

解决方案


下面应该工作。我将数据拆分为一个由换行符分隔的向量\\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}"

推荐阅读