繁体   English   中英

r- grepl 以任何顺序查找匹配的字符串

[英]r- grepl to find matching strings in any order

我有一个匹配的字符串。 需要查找匹配多个字符串(全部/全部)和任意顺序的文本:

Text1: "I have no intention to make illegal parking along the road or cause obstruction."

Text2: "I have no intention to make illegal parking along the road or cause damage."

我的代码:

    mynames=c("illegal parking" , "obstruction")
grepl(paste(mynames, collapse='|'), Text1, ignore.case=TRUE)

当我通过Text1Text2 - 我得到TRUE - 对于两者; 但是我需要TRUEText1FALSEText2 当只有两个字符串都存在时,它应该会产生 - 它可以在文本中以任何顺序出现。

| 在正则表达式中的意思是“或”。 这就是为什么它在两个文本上都是 TRUE 的。 您必须测试是否在"illegal parking"之后(中间有或没有任何东西)是"obstruction" ,在正则表达式中这是"illegal parking.*obstruction" ,或者如果你有相反的方式,所以"illegal parking.*obstruction|obstruction.*illegal parking"

grepl("illegal parking.*obstruction|obstruction.*illegal parking", Text1, ignore.case=TRUE)

您可以测试str_extract_all()的结果以查看两者是否匹配。 这种方法意味着您不必担心订单。

library(stringr)
library(purrr)

map_lgl(str_extract_all(c(Text1, Text2), paste(mynames, collapse='|')), ~all(mynames %in% .x))

[1] TRUE FALSE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM