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
  • 46,523
  • 6
  • 46
  • 87
HeavyBulb
  • 63
  • 6

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
  • 8,933
  • 1
  • 6
  • 21