Multiple regexpr in one string in R

前端 未结 2 865
粉色の甜心
粉色の甜心 2020-12-11 04:46

So I have a really long string and I want to work with multiple matches. I can only seem to get the first position of the first match using regexpr. How can I g

2条回答
  •  清歌不尽
    2020-12-11 05:42

    Using gregexpr allows for multiple matches.

    > x <- c("only one match", "match1 and match2", "none here")
    > m <- gregexpr("match[0-9]*", x)
    > m
    [[1]]
    [1] 10
    attr(,"match.length")
    [1] 5
    attr(,"useBytes")
    [1] TRUE
    
    [[2]]
    [1]  1 12
    attr(,"match.length")
    [1] 6 6
    attr(,"useBytes")
    [1] TRUE
    
    [[3]]
    [1] -1
    attr(,"match.length")
    [1] -1
    attr(,"useBytes")
    [1] TRUE
    

    and if you're looking to extract the match you can use regmatches to do that for you.

    > regmatches(x, m)
    [[1]]
    [1] "match"
    
    [[2]]
    [1] "match1" "match2"
    
    [[3]]
    character(0)
    

提交回复
热议问题