Reputation: 52558
How can we make stringr functions (like str_replace
) treat arguments as string literals rather than regex without escaping special characters manually?
Escaping special characters works as expected
"dsfj?lddkfj" %>% str_replace("\\?ld", "AAA")
[1] "dsfjAAAdkfj"
But if we don't escape the special character(s), stringr
functions treat the pattern
as a regex. In this case we get an error.
"dsfj?lddkfj" %>% str_replace("?ld", "AAA")
Is there some standard way to force stringr functions to treat patterns as string literals (without escaping special characters manually)?
I can see perl = T
is an option used for the function sub()
Upvotes: 1
Views: 1086
Reputation: 887611
We can use sub
in base R
sub("?ld", "AAA", "dsfj?lddkfj", fixed = TRUE)
#[1] "dsfjAAAdkfj"
Upvotes: 0
Reputation: 389175
Wrap the pattern in fixed()
library(stringr)
"dsfj?lddkfj" %>% str_replace(fixed("?ld"), "AAA")
#[1] "dsfjAAAdkfj"
Upvotes: 5