如何匹配所有以plan_
开头且不以template
结尾的单词,而不使用invert = TRUE
?在下面的示例中,我只想匹配第二个字符串。 我尝试了负向先行断言,但它不起作用,可能是因为贪婪性?
names <- c("plan_x_template", "plan_x")
grep("^plan.*(?!template)$",
names,
value = TRUE, perl = TRUE
)
#> [1] "plan_x_template" "plan_x"
我的意思是,也可以通过两个正则表达式调用来解决这个问题,但我想看看另一种方法的工作原理 :-)
is_plan <- grepl("^plan_", names)
is_template <- grepl("_template$", names)
names[is_plan & !is_template]
#> [1] "plan_x"
grep("^plan_[A-Za-z]+\\b", names, value = TRUE)
对你来说有效吗? - undefined