与 NEAR 正则表达式和多个术语匹配的字符串

问题描述 投票:0回答:1

我有一个包含一些字符串的向量,如下所示:

test_strings <- c("this string referring to dummy text should be matched", 
                  "this string referring to an example of code should be matched",
                  "this string referring to texts which are kind of dumb should be matched",
                  "this string referring to an example, but with a really long gap before mentioning a word such as 'text' should not be matched")

我有两个搜索词列表:

list_a <- c("dummy", "dumb", "example", "examples")
list_b <- c("text", "texts", "script", "scripts", "code")

我想返回匹配,其中存在来自 list_a 的字符串和来自 list_b 的字符串的某种组合,这些字符串彼此出现在 10 个单词以内(即 test_strings 的元素 1-3)。

基于这个问题的有用答案:R - 使用 NEAR 正则表达式搜索文本,我能够实现“NEAR”功能,但是一旦我包含多个术语,我的代码就无法返回正确的匹配项,其中一些是子串。

这是我到目前为止尝试过的:

regex_string <- "\\b(?:(dum|example)\\W+(?:\\w+\\W+){0,10}?(text|script|code)|(text|script|code)\\W+(?:\\w+\\W+){0,10}?(dum|example))\\b"

test_results <- test_strings[grepl(regex_string,test_strings, ignore.case=TRUE)]

test_results

只返回完全匹配的字符串——即“这个引用代码示例的字符串应该匹配”

regex_string <- "\\b(?:(dum.*|example.*)\\W+(?:\\w+\\W+){0,10}?(text.*|script.*|code)|(text.*|script.*|code)\\W+(?:\\w+\\W+){0,10}?(dum.*|example.*))\\b"

test_results <- test_strings[grepl(regex_string,test_strings, ignore.case=TRUE)]

test_results

允许我匹配子字符串,这样“这个引用虚拟文本的字符串应该被匹配”,“这个引用代码示例的字符串应该被匹配”和“这个引用文本的字符串应该被匹配”是退货了

然而,“这个字符串指的是一个例子,但在提到诸如‘文本’之类的词之前有一个很长的间隙不应该被匹配”也被返回,我猜因为包含“。*”在某种程度上使 0 无效-10 字限制。

关于如何解决这个问题的任何想法?

r regex string-matching grepl
1个回答
0
投票

你必须使用正则表达式吗?

sapply(
  strsplit(test_strings, "[^A-Za-z]+"),
  function(st) {
    tmp <- outer(na.omit(match(list_b, st)), na.omit(match(list_a, st)), `-`)
    any(tmp > 0 & tmp <= 10)
  })
# [1]  TRUE  TRUE  TRUE FALSE

这表明

test_strings
的前三个有来自
list_b
的东西出现 10 个或更少来自
list_a
的东西,而第四个元素没有。

© www.soinside.com 2019 - 2024. All rights reserved.