gsub return an empty string when no match is found

后端 未结 7 1657
太阳男子
太阳男子 2021-01-12 04:35

I\'m using the gsub function in R to return occurrences of my pattern (reference numbers) on a list of text. This works great unless no match is found, in whic

7条回答
  •  轮回少年
    2021-01-12 05:02

    Another simple way is to use gsub but specify you want '' in a new function

    noFalsePositives <- function(a,b,x) {
      return(ifelse(gsub(a,b,x)==x,'',gsub(a,b,x)))
    }
    # usage
    noFalsePositives(".*(Ref. (\\d+)).*", "\\1", data)
    # [1] "Ref. 12" "" 
    

提交回复
热议问题