Sub returns invalid data

I have the following code snippet:

temp <- "44C"
sub("^([-+]?[0-9]+)([CF])$","\\2",temp)

This returns C correctly .

But when I try

temp <- "44"
sub("^([-+]?[0-9]+)([CF])$","\\2",temp)

I was expecting an empty vector. Instead, I get " 44 ".

Am I reasoning something wrong?

+4
source share
2 answers

In your second case, no \2. Therefore, it cannot replace anything and returns the original string without changes. When no re-expression is performed on the sub element, the original string is returned.

+5
source

It will work if you add ?to your regular expression:

temp <- c("44C", "44")
sub("^([-+]?[0-9]+)([CF])?$","\\2",temp)
# [1] "C" "" 
+2
source

All Articles