首页 > 解决方案 > 使用 stringr::str_detect 检测字符串是否在字符出现 4 次后出现

问题描述

不确定我的问题措辞是否很好,但它本质上是我想要做的。

数据示例:

Data <- c("NELIG_Q1_1_C1_A", "NELIG_N1_1_EG1_B", "NELIG_V2_1_NTH_C", "NELIG_Q2_1_C5_Q",
"NELIG_N1_1_C1_RA", "NELIG_Q1_1_EG1_QR", "NELIG_V2_1_NTH_PQ", "NELIG_N2_1_C5_PRQ")

我想str_detect在最后一组字母组合上使用 a 进行过滤。在我要查找的字符串/模式之前总会有四个“_”,但在第四个“_”之后可能有许多不同的字母组合。在上面的例子中,我试图只检测字母“Q”。

如果我做一个简单的 Data2 <- Data %>% filter(str_detect(column, "Q"))我会得到所有在字符串中任何地方都有 Q 的行。我怎么能告诉它只关注最后一部分?

标签: rstringrstringi

解决方案


如果我正确理解您的问题,那么您可以执行以下操作:

library(stringr)
str_detect(Data, ".*_.*_.*_.*_.*Q.*$")
#R> [1] FALSE FALSE FALSE  TRUE FALSE  TRUE  TRUE  TRUE

这将检测第四个“_”之后是否有任何“Q”。

看标题:

在 4 个常量字符后检测字符串

然后你可以做一个这样的通用函数:

# returns TRUE if a certain character occurs after a character has been 
# there four times.
# 
# Args: 
#   x characters to check.
#   what character to occur at the end. 
#   after character to occur four times.
detect_after_four_times <- function(x, what, after){
  reg <- sprintf(".*%s.*%s.*%s.*%s.*%s.*$", after, after, after, after, 
                 what)
  str_detect(x, reg)
}

detect_after_four_times(Data, "Q", "_")
#R> [1] FALSE FALSE FALSE  TRUE FALSE  TRUE  TRUE  TRUE
detect_after_four_times(Data, "R", "_") # look for R instead
#R> [1] FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE  TRUE

# also works if there are only three times of "after"
detect_after_four_times("only_three_dashes_Q", "Q", "_")
#R> [1] FALSE

推荐阅读