匹配字符串的开头但不以R结尾

时间:2018-07-16 17:43:01

标签: r regex

如何在不使用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"

1 个答案:

答案 0 :(得分:4)

您可以使用

names <- c("plan_x_template", "plan_x")
grep("^plan(?!.*template)", 
  names, 
  value = TRUE, perl = TRUE
)

请参见R online demo

^plan(?!.*template)模式匹配:

  • ^-字符串的开头
  • plan-一个plan子字符串
  • (?!.*template)-如果negative lookahead匹配失败,并且在当前位置的左侧紧接换行符以外还有0+个字符(因为使用了perl = TRUE,并且模式是使用PCRE引擎处理的,与默认的. TRE regex引擎相反,grep并不匹配所有可能的字符),其后跟template子字符串。

注意:如果是多行字符串,则需要在正则表达式"(?s)^plan(?!.*template)"中使用DOTALL修饰符。

相关问题