Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitizing string for grepl

Tags:

regex

r

escaping

Please consider the following

vector <- c("C++", "Abba", "Beatles", "C++")
string <- vector[1]

grepl(string,vector)

# Error in grepl(string, vector) : 
#  invalid regular expression 'C++', reason 'Invalid use of repetition operators'

I need a function to sanitize my vector before passing it to regex.

I tried to write adapt a regex function from JavaScript but without success.

regexSanitized <- function(string) {
  return(gsub("/[#-}]/g", "\\$&", string))
}
like image 681
CptNemo Avatar asked Oct 22 '25 22:10

CptNemo


1 Answers

I figured I'd throw this down as an answer:

Use: grepl(string, vector, fixed = TRUE) or possibly vector %in% string and forgo regex all together.

like image 101
Tyler Rinker Avatar answered Oct 24 '25 12:10

Tyler Rinker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!