Regex match exact number of letters

后端 未结 4 964
离开以前
离开以前 2020-12-21 15:51

Let\'s say I want to find all words in which letter \"e\" appears exactly two times. When I define this pattern:

pattern1 <- \"e.*e\" 
grep(pattern1, stri         


        
4条回答
  •  臣服心动
    2020-12-21 16:46

    You may use:

    ^(?:[^e]*e){2}[^e]*$
    

    See the regex demo. The (?:...) is a non-capturing group that allows quantifying a sequence of subpatterns and is thus easily adjustable to match 3, 4 or more specific sequences in a string.

    Details

    • ^- start of string
    • (?:[^e]*e){2} - 2 occurrences of
      • [^e]* - any 0+ chars other than e
      • e - an e
    • [^e]* - any 0+ chars other than e
    • $ - end of string

    See the R demo below:

    x <- c("feel", "agre", "degree")
    rx <- "^(?:[^e]*e){2}[^e]*$"
    grep(rx, x, value = TRUE)
    ## => [1] "feel"
    

    Note that instead of value = T it is safer to use value = TRUE as T might be redefined in the code above.

提交回复
热议问题