首页 > 解决方案 > 访问 gregexpr 的结果

问题描述

我想使用 gregexpr 函数来查找字符串中子字符串的开始和结束位置。该函数在控制台中运行良好,但我无法访问起始位置或字符串长度的结果:

g <- gregexpr("e", "cheese")

g

[[1]]
[1] 3 4 6
attr(,"match.length")
[1] 1 1 1
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE

g[[1]][1]仅显示第一个值 (3),但我需要创建一个向量,其中包含起始位置和长度的所有值。谢谢。

标签: r

解决方案


您可以通过这种方式提取它们:

g <- gregexpr("e", "cheese")

# one liner for : starts <- g[[1]]
#                 attributes(starts) <- NULL
starts <- `attributes<-`(g[[1]],NULL) 

lens <- attr(g[[1]],'match.length')

> starts
[1] 3 4 6
> lens
[1] 1 1 1

当然,这仅适用于文本长度为 1 的情况(如示例中所示,因为它仅包含"cheese")。否则,您将需要遍历gusing g[[2]]g[[3]]...等的元素。


推荐阅读