gsub return an empty string when no match is found

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

    based on @joran 's answer

    function:

    extract_matches <- function(x,pattern,replacement,replacement_nomatch=""){
        x <- gsub(pattern,replacement,x)
        x[-grep(pattern,x,value = FALSE)] <- replacement_nomatch
        x
    }
    

    usage:

    data <- list("with citation (Ref. 12)", "without reference", "")
    extract_matches(data,  ".*(Ref. (\\d+)).*", "\\1")
    

提交回复
热议问题