在R中的正则表达式中使用变量值

马克·R

如何在R中一起使用变量值和正则表达式位置表达式?例如,在下面的代码中,我将如何仅替换出现在字符串开头或结尾的“ zzz”的情况?这适用于“ zzz”的所有值

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)
蒂姆·古德曼

您需要^$字符位于正则表达式模式字符串中。换句话说,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, '$'))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章