R: How to ignore case when using str_detect?

后端 未结 4 1415
深忆病人
深忆病人 2020-12-14 16:22

stringr package provides good string functions.

To search for a string (ignoring case)

one could use

stringr::str_detect(\'TOYOTA subaru\',ig         


        
相关标签:
4条回答
  • 2020-12-14 16:46

    the search string must be inside function fixed and that function has valid parameter ignore_case

    str_detect('TOYOTA subaru', fixed('toyota', ignore_case=TRUE))
    
    0 讨论(0)
  • 2020-12-14 16:49

    You can save a little typing with (?i):

    c("Toyota", "my TOYOTA", "your Subaru") %>% 
      str_detect( "(?i)toyota" )
    # [1]  TRUE  TRUE FALSE
    
    0 讨论(0)
  • 2020-12-14 16:57

    You can use the base R function grepl() to accomplish the same thing without a nested function. It simply accepts ignore.case as an argument.

    grepl("toyota", 'TOYOTA subaru', ignore.case = TRUE)
    

    (Note that the order of the first two arguments (pattern and string) are switched between grepl and str_detect).

    0 讨论(0)
  • 2020-12-14 17:04

    You can use regex (or fix as @lmo's comments depending on what you need) function to make the pattern as detailed in ?modifiers or ?str_detect (see the instruction for pattern parameter):

    library(stringr)
    str_detect('TOYOTA subaru', regex('toyota', ignore_case = T))
    # [1] TRUE
    
    0 讨论(0)
提交回复
热议问题