【问题标题】:Using variable value in regex in R在 R 的正则表达式中使用变量值
【发布时间】:2017-07-19 00:38:52
【问题描述】:

如何在 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)

【问题讨论】:

    标签: r regex str-replace gsub


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 2020-04-27
      • 1970-01-01
      相关资源
      最近更新 更多