54

stringr package provides good string functions.

To search for a string (ignoring case)

one could use

stringr::str_detect('TOYOTA subaru',ignore.case('toyota'))

This works but gives warning

Please use (fixed|coll|regex)(x, ignore_case = TRUE) instead of ignore.case(x)

What is the right way of rewriting it?

Braiam
  • 1
  • 11
  • 47
  • 78
userJT
  • 11,486
  • 20
  • 77
  • 88

5 Answers5

62

You can use regex (or fixed as suggested in @lmo's comment 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
giocomai
  • 3,043
  • 21
  • 24
Psidom
  • 209,562
  • 33
  • 339
  • 356
36

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

c("Toyota", "my TOYOTA", "your Subaru") %>% 
  str_detect( "(?i)toyota" )
# [1]  TRUE  TRUE FALSE
David T
  • 1,993
  • 10
  • 18
  • 8
    This is the best answer in for both single and multiple search terms. For example, ```str_detect(X, (?i)cws|usgs|fws)``` – Jessica Burnett Jun 17 '21 at 17:58
  • I frequently use this with `str_subset()`. It has saved me a lot of typing. – San Jun 20 '21 at 05:07
  • (?i) may also be used with `data.table` `%like%` operator for case-insensitive search. Or you may just use `%ilike%` operator which has been made specifically for case-insensitive search. – San Jun 20 '21 at 05:41
  • Is '(?i)' a way in the original regular expressions? – Jiaxiang Aug 02 '21 at 15:09
30

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))
userJT
  • 11,486
  • 20
  • 77
  • 88
8

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).

Sam Firke
  • 21,571
  • 9
  • 87
  • 105
1

Or you can erase all capitalization while you search:

str_detect(tolower('TOYOTA subaru'), 'toyota')
Unrelated
  • 347
  • 2
  • 14