I am trying to match string LLC
from a list. The string could be any combination with upper and lower cases, such as llc
,Llc
,llC
. How to construct a regular expression that include all possible upper/lower case combinations of the string? Many thanks!
CodePudding user response:
1. base
In the series of pattern matching functions in base
(grep()
, sub()
, etc.), you could set the argument ignore.case
to control case-sensitivity.
x <- c('Llc', 'lLc', 'llC')
grepl('LLC', x, ignore.case = TRUE)
# [1] TRUE TRUE TRUE
You could also insert (?i)
to switch on case-insensitive mode. ((?-i)
to switch off)
grepl('(?i)LLC', x)
# [1] TRUE TRUE TRUE
2. stringr
With stringr
, you could control matching behaviour with modifier functions. (regex()
, fixed()
, etc.)
str_detect(x, regex('LLC', ignore_case = TRUE))
# [1] TRUE TRUE TRUE