stevec
stevec

Reputation: 52558

How to get str_replace (and other stringr) functions to ignore regex (treat string literally)?

How can we make stringr functions (like str_replace) treat arguments as string literals rather than regex without escaping special characters manually?

Example

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")

Quesiton

Is there some standard way to force stringr functions to treat patterns as string literals (without escaping special characters manually)?

Notes

I can see perl = T is an option used for the function sub()

Upvotes: 1

Views: 1086

Answers (2)

akrun
akrun

Reputation: 887611

We can use sub in base R

sub("?ld", "AAA", "dsfj?lddkfj", fixed = TRUE)
#[1] "dsfjAAAdkfj"

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

Wrap the pattern in fixed()

library(stringr)

"dsfj?lddkfj" %>% str_replace(fixed("?ld"), "AAA")
#[1] "dsfjAAAdkfj"

Upvotes: 5

Related Questions