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

use*_*rJT 16 r stringr

stringr包提供了良好的字符串函数.

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

一个人可以用

stringr::str_detect('TOYOTA subaru',ignore.case('toyota'))
Run Code Online (Sandbox Code Playgroud)

这有效,但会发出警告

请使用(fixed | coll | regex)(x,ignore_case = TRUE)而不是ignore.case(x)

重写它的正确方法是什么?

Psi*_*dom 19

您可以使用regex(或fix作为@ lmo的注释,具体取决于您的需要)函数来制作模式,如?modifiers或?str_detect中所详述(请参阅模式参数的说明):

library(stringr)
str_detect('TOYOTA subaru', regex('toyota', ignore_case = T))
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)

  • 或者使用`fixed`:`str_detect('TOYOTA subaru',fixed('toyota',ignore_case = TRUE))`. (3认同)

Dav*_*d T 14

您可以使用以下命令节省一点打字时间(?i)

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

  • 这是单个和多个搜索词的最佳答案。例如,``str_detect(X, (?i)cws|usgs|fws)```` (9认同)

use*_*rJT 11

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

str_detect('TOYOTA subaru', fixed('toyota', ignore_case=TRUE))
Run Code Online (Sandbox Code Playgroud)


Sam*_*rke 8

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

grepl("toyota", 'TOYOTA subaru', ignore.case = TRUE)
Run Code Online (Sandbox Code Playgroud)

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