r grep by regex - finding a string that contains a sub string exactly one once

前端 未结 6 1876
暗喜
暗喜 2021-01-25 22:10

I am using R in Ubuntu, and trying to go over list of files, some of them i need and some of them i don\'t need,

I try to get the one\'s i need by finding a sub string

6条回答
  •  粉色の甜心
    2021-01-25 22:40

    It looks like you're after strings with one a and no more, regardless where in the string. While stringi can accomplish the task, a base solution would be:

    s <- c("a", "aa", "aca", "", "b", "ba", "ab")
    
    m <- gregexpr("a", s)
    s[lengths(regmatches(s, m)) == 1]
    
    [1] "a"  "ba" "ab"
    

    Alternatively, a regex-lite approach:

    s[vapply(strsplit(s, ""), function(x) sum(x == "a") == 1, logical(1))]
    [1] "a"  "ba" "ab"
    

提交回复
热议问题