2017-07-19 83 views
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) 

回答

2

您需要^$字符是正則表達式字符串中。換句話說,target_nos可能是這樣的:

"^1" "^2" "^zzz" "^4" "1$" "2$" "zzz$" "4$" 

要實現這樣的編程方式從你有什麼,你可以這樣做:

target_nos <- c("1","2","zzz","4") 
target_nos <- c(paste0('^', target_nos), paste0(target_nos, '$'))