0
x = c("a | b", "a b", "a,  b", "a,b", "a.b")

str_replace_all(x, "  |  ", ", ") 

the desired output is:

"a, b", "a b", "a,  b", "a,b", "a.b"

but I'm not sure how to keep stringr (or gsub) from thinking its the "or" operator instead of an annoying character I'm trying to clean up from my dataset.

s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • You either need to escape the special character with two backslashes, or (more efficiently) since you are doing a direct, exact replacement, not using any regex pattern matching, you can indicate that your pattern is **fixed**, either by using the `fixed = TRUE` argument of `sub` or `gsub` or wrapping your pattern in `stringr::fixed()`. – Gregor Thomas Feb 22 '23 at 15:26

1 Answers1

1

You need to escape | (which is a regex metacharacter signifying alternation):

str_replace_all(x, " \\|", ",")
[1] "a, b"  "a b"   "a,  b" "a,b"   "a.b" 
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34