gsub return an empty string when no match is found

后端 未结 7 1610
太阳男子
太阳男子 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:14

    according to the documentation, this is a feature of gsub it returns the input string if there are no matches to the supplied pattern matches returns the entire string.

    here, I use the function grepl first to return a logical vector of the presence/absence of the pattern in the given string:

    ifelse(grepl(".*(Ref. (\\d+)).*", data), 
          gsub(".*(Ref. (\\d+)).*", "\\1", data), 
          "")
    

    embedding this in a function:

    mygsub <- function(x){
         ans <- ifelse(grepl(".*(Ref. (\\d+)).*", x), 
                  gsub(".*(Ref. (\\d+)).*", "\\1", x), 
                  "")
         return(ans)
    }
    
    mygsub(data)
    

提交回复
热议问题