Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sub returns incorrect data

Tags:

regex

r

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?

like image 994
chribonn Avatar asked Mar 19 '23 15:03

chribonn


1 Answers

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.

like image 189
vks Avatar answered Mar 24 '23 14:03

vks