看起来grep在返回匹配项方面是“贪婪的”。假设我有以下数据:
Sources <- c(
"Coal burning plant",
"General plant",
"coalescent plantation",
"Charcoal burning plant"
)
Registry <- seq(from = 1100, to = 1103, by = 1)
df <- data.frame(Registry, Sources)
如果执行grep("(?=.*[Pp]lant)(?=.*[Cc]oal)", df$Sources, perl = TRUE, value = TRUE)
,它将返回
"Coal burning plant"
"coalescent plantation"
"Charcoal burning plant"
但是,我只想返回完全匹配的内容,即仅在出现“煤”和“植物”的地方。我不要“聚光灯”,“种植园”等。因此,我只想看看"Coal burning plant"
您想\b
在单词样式周围使用单词边界。单词边界不占用任何字符。它断言,一侧有文字字符,而另一侧没有文字字符。您可能还需要考虑使用inline(?i)
修饰符进行不区分大小写的匹配。
grep('(?i)(?=.*\\bplant\\b)(?=.*\\bcoal\\b)', df$Sources, perl=T, value=T)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句