r - 在 R 中使用 AND 和 OR 布尔运算符检测字符串
问题描述
我有这样的文字:
text = 'I love apple, pear, grape and peach'
如果我想知道文本是否包含apple
或pear
。我可以执行以下操作并且工作正常:
str_detect(text,"apple|pear")
[1] TRUE
我的问题是如果我想像这样使用布尔值怎么办(apple OR pear) AND (grape)
。无论如何我可以把它放进去str_detect()
。那可能吗?以下不工作:
str_detect(text,"(apple|pear) & (grape)" )
[1] FALSE
我想知道这一点的原因是我想编程转换一个“布尔查询”并输入grep
or str_detect
。就像是:
str_detect(text, '(word1|word2) AND (word2|word3|word4) AND (word5|word6) AND .....')
数量AND
不一......
请没有解决方案str_detect
。
解决方案
您可以将所有模式作为向量传递给 str_detect 并检查它们是否都TRUE
带有all
.
patterns <- c('apple|pear', 'grape')
all(str_detect(text, patterns))
或以 R 为基数
all(sapply(patterns, grepl, x = text))
或者,您可以将模式放在列表中并使用映射,这将为 OR 提供更详细的输出(或您可能想要作为列表元素放置的任何其他内容)
patterns <- list(c('apple', 'pear'), 'peach')
patterns %>%
map(str_detect, string = text)
# [[1]]
# [1] TRUE TRUE
#
# [[2]]
# [1] TRUE
也可以将其编写为单个正则表达式,但我认为没有理由这样做
patterns <- c('apple|pear', 'grape')
patt_combined <- paste(paste0('(?=.*', patterns, ')'), collapse = '')
str_detect(text, patt_combined)
patt_combined
是
# [1] "(?=.*apple|pear)(?=.*grape)"
推荐阅读
- c# - OpenGL 4 - 欧拉旋转没有任何意义
- git - 如何从 VScode 工作区中删除 SCM 图标?
- pdf - 要求字母连词的 unicode
- json - 使用 Anypoint Studio 转换 EMS 队列消息并插入数据库
- java - 未找到测试 - 使用 JUnit5 [in IntelliJ IDEA] 时
- python - 在 python 中,为什么我的实例变量在方法中被引用后会发生变化?
- java - 使用自定义 DiskSpaceHealthIndicator(Spring Boot Actuator)?
- macos - 带有 TextField 的 macOS SwiftUI 弹出框在首次编辑时关闭
- php - Wordpress中的php mssql连接问题
- python - 无法为石墨烯设置“SCHEMA”导入“art_project.schema.schema”。ImportError:无法导入名称“DjangoFilterConnectionField”