Regex match exact number of letters

后端 未结 4 966
离开以前
离开以前 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:34

    We can use a pattern to match zero or more characters that are not 'e' ([^e]*) from the start (^) of the string, followed by character 'e', then another set of characters that are not 'e' followed by 'e', and zero or more characters not an 'e' until the end ($) of the string

    res <- grep("^[^e]*e[^e]*e[^e]*$", stringr::words, value = TRUE)
    stringr::str_count(res, "e")
    #[1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
    #[58] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
    #[115] 2 2 2 2 2 2 2
    

提交回复
热议问题