0

So, I want to extract the substring of a string like this mystr <- "aa/bb/cc?rest"

I found the sub() function but executing sub("?.*", "", mystr) returns "" instead of "aa/bb/cc".

Why?

The reason is obviousyl because of ? being a special character but using backticks or "\?" doesn't solve this problem.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
HeavyBulb
  • 123
  • 9

1 Answers1

1

You need double \ for escaping:

> mystr <- "aa/bb/cc?rest"
> sub("\?.*", "", mystr)
Error: '\?' is an unrecognized escape in character string starting ""\?"
> sub("\\?.*", "", mystr)
[1] "aa/bb/cc"
danlooo
  • 10,067
  • 2
  • 8
  • 22