似乎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"
发布于 2014-06-16 02:34:05
您希望围绕您的单词模式使用单词边界\b。单词边界不消耗任何字符。它断言,一边有一个字字,另一边没有字。您还可以考虑使用内联(?i)修饰符进行不区分大小写的匹配。
grep('(?i)(?=.*\\bplant\\b)(?=.*\\bcoal\\b)', df$Sources, perl=T, value=T)Working Demo
发布于 2014-06-16 02:16:52
如果你总是想要“煤”然后“工厂”,那么这应该是可行的。
grep("\\b[Cc]oal\\b.*\\b[Pp]lant\\b", Sources, perl = TRUE, value=T)在这里,我们添加\b匹配,它代表一个单词边界。你可以在你最初的尝试中添加“边界”这个词--我们很好
grep("(?=.*\\b[Pp]lant\\b)(?=.*\\b[Cc]oal\\b)", Sources,
perl = TRUE, value = TRUE)https://stackoverflow.com/questions/24235574
复制相似问题