简体   繁体   中英

sub returns incorrect data

I have the following chunk of code:

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

This correctly returns C .

Yet when I try out

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

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

Am I reasoning something wrong?

There is no \\2 in your second case.So it cannot replace anything and returns the original string unaltered. When a regex fails in sub then the original string is returned.

It will work if you add ? to your regex:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM