R 中的 gsub 和 sub 不工作

gsub and sub in R not working

我有字符日期

aa <- '2/3/2015'
qq <- gsub('\d+\/\d+\/\d+{4}', '', aa)

但是qqreturns""

我做错了什么?我也尝试使用 sub() 函数,但它们都导致 "".

我希望结果是 '2/3/2015' 而不是 ""

OP可以使用的正确函数是grep

aa <- '2/3/2015'
qq <- grep('\d+\/\d+\/\d+{4}', aa,value = TRUE )
qq
#[1] "2/3/2015"

#Same thing can be achieved by gsub or sub as:
qq <- gsub('(\d+\/\d+\/\d+{4})', '\1', aa )
qq
#[1] "2/3/2015"

#OR even you can try
qq <- gsub('(\d+\/\d+\/\d+{4})', 'Date: \1', aa )
qq
#[1] "Date: 2/3/2015"

#The real use of gsub/sub is when one need partial string as:
qq <- gsub('\d+\/\d+\/(\d+{4})', 'Year: \1', aa )
qq
#[1] "Year: 2015"