R grep: Match one string against multiple patterns

前端 未结 3 1714
长发绾君心
长发绾君心 2020-12-04 18:01

In R, grep usually matches a vector of multiple strings against one regexp.

Q: Is there a possibility to match a single string against multiple regexps? (wi

3条回答
  •  死守一世寂寞
    2020-12-04 19:02

    To expand on the other answer, to transform the sapply() output into a useful logical vector you need to further use an apply() step.

    keywords <- c("dog", "cat", "bird")
    strings <- c("Do you have a dog?", "My cat ate by bird.", "Let's get icecream!")
    (matches <- sapply(keywords, grepl, strings, ignore.case=TRUE))
    #        dog   cat  bird
    # [1,]  TRUE FALSE FALSE
    # [2,] FALSE  TRUE  TRUE
    # [3,] FALSE FALSE FALSE
    

    To know which strings contain any of the keywords (patterns):

    apply(matches, 1, any)
    # [1]  TRUE  TRUE FALSE
    

    To know which keywords (patterns) were matched in the supplied strings:

    apply(matches, 2, any)
    #  dog  cat bird 
    # TRUE TRUE TRUE
    

提交回复
热议问题