任何需要两个匹配项而不是只有一个匹配项的方法都可以使用grepl实现TRUE



我试图使用grepl检测术语,但我得到了太多的误报。我希望有一种方法可以要求列表外任何术语的两次成功匹配(我对我的一段数据进行了手动编码,并试图使自动化至少大致对应于此,但我的阳性结果是手动编码的5倍)。我不认为grepl接受任何需要一个以上匹配才能触发TRUE的论点。有没有什么方法可以要求两个匹配项才能触发TRUE结果?或者我应该使用其他功能吗?

GenericColumn <- cbind(grepl(Genericpattern, Statement$Statement.Text, ignore.case = TRUE))

编辑:

这里有一个更具体的例子:

Examplepattern <- 'apple|orange'
ExampleColumn <- cbind(grepl(Examplepattern, Rexample$Statement.Text, ignore.case = TRUE)) 

现在,所有这些都将在grepl中触发true。我只希望有两个引用的项目触发true。

示例数据:

Rexample <- structure(list(Statement.Text = structure(c(2L, 1L, 3L, 5L, 4L
), .Label = c("This apple is a test about an apple.", "This is a test about apples.", 
"This orange is a test about apples.", "This orange is a test about oranges.", 
"This orange is a test."), class = "factor")), .Names = "Statement.Text", row.names = c(NA, 
5L), class = "data.frame")

所需输出:TRUE、FALSE、TRUE、TRUE、FALSE

您可以指定您希望在带有大括号的regex中重复某些内容的次数,如{2}(无论之前是什么,都是两次)、{2,5}(2-5次)或{2,}(2次或更多次)。但是,您需要允许要匹配的单词之间的单词,因此您需要用*量化的通配符.(0次或更多次)。

因此,如果您希望appleorange匹配两次(包括appleorange,反之亦然),则可以使用

grepl('(apple.*|orange.*){2}', Rexample$Statement.Text, ignore.case = TRUE)
# [1] FALSE  TRUE  TRUE FALSE  TRUE

如果您希望apple重复两次或orange重复两次(但不希望apple重复一次和orange重复一次),请分别量化:

grepl('(apple.*){2,}|(orange.*){2}', Rexample$Statement.Text, ignore.case = TRUE)
# [1] FALSE  TRUE FALSE FALSE  TRUE

您可以再次尝试显式查找模式的正则表达式,如(?:apple|orange).*(?:apple|orange)

(pattern <- paste0("(?:", Examplepattern, ")", ".*", "(?:", Examplepattern, ")"))
#[1] "(?:apple|orange).*(?:apple|orange)"

grepl(pattern, Rexample$Statement.Text, ignore.case = TRUE, perl = TRUE)
#[1] FALSE  TRUE  TRUE FALSE  TRUE

相关内容

最新更新