2
如何在R中一起使用變量值和正則表達式位置表達式?例如,在下面的代碼中,我將如何替換僅出現在字符串開頭或結尾的「zzz」的情況?這適用於「zzz」的所有值在R中使用正則表達式中的變量值
target_nos <- c("1","2","zzz","4")
sample_text <- cbind("1 dog 1","3 cats zzz","zzz foo 1")
for (i in 1:length(target_nos))
{
sample_text <- gsub(pattern = target_nos[i],replacement = "REPLACED", x =
sample_text)
}
但是,如何包含^和$位置標記?這將引發錯誤
sample_text <- gsub(pattern = ^target_nos[1],replacement = "REPLACED", x =
sample_text)
這將運行,但是從字面上解釋變量,而不是調用值
sample_text <- gsub(pattern = "^target_nos[1]", replacement = "REPLACED", x =
sample_text)