使用str_detect时如何忽略大小写?

How to ignore case when using str_detect?

stringr 包提供了很好的字符串函数。

搜索字符串(忽略大小写)

有人会用

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

这有效但会发出警告

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

正确的改写方式是什么?

您可以使用 regex(或 @lmo 的评论中建议的 fixed,具体取决于您的需要)函数来制作 ?modifiers 或 ?[ 中详述的模式=17=](看模式参数说明):

library(stringr)
str_detect('TOYOTA subaru', regex('toyota', ignore_case = T))
# [1] TRUE

搜索字符串必须在函数 fixed 内并且该函数具有有效参数 ignore_case

str_detect('TOYOTA subaru', fixed('toyota', ignore_case=TRUE))

您可以使用基本 R 函数 grepl() 来完成同样的事情,而无需嵌套函数。它只接受 ignore.case 作为参数。

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

(请注意,前两个参数(模式和字符串)的顺序在 greplstr_detect 之间切换)。

您可以使用 (?i) 节省一些打字时间:

c("Toyota", "my TOYOTA", "your Subaru") %>% 
  str_detect( "(?i)toyota" )
# [1]  TRUE  TRUE FALSE

或者您可以在搜索时删除所有大写:

str_detect(tolower('TOYOTA subaru'), 'toyota')