【问题标题】:Finding strings that are a certain length and contain specific characters查找具有特定长度并包含特定字符的字符串
【发布时间】:2018-11-14 23:22:10
【问题描述】:

样本数据

a<-c("hour","four","ruoh", "six", "high", "our")

我想查找所有包含 o & u & h & 的字符串都是 4 个字符,但顺序无关紧要。

我要回"hour","four","ruoh" 这是我的尝试

grepl("o+u+r", a) nchar(a)==4

【问题讨论】:

  • 如何分别测试。您首先测试(使用 grep)向量的哪些元素包含“o”,通过的人,您测试他们是否有“u”,通过的人测试“h”。
  • @Cris 这是最简单的方法吗?
  • “四”不包含o&u&h。
  • @neilfws 我已经做了修改
  • Regular Expressions: Is there an AND operator?; grepl("(?=.*h)(?=.*o)(?=.*u)", a, perl = TRUE)

标签: r string grepl


【解决方案1】:

要匹配 长度为 4 且包含字符 hou 的字符串,请使用:

grepl("(?=^.{4}$)(?=.*h)(?=.*o)(?=.*u)",
      c("hour","four","ruoh", "six", "high", "our"),
      perl = TRUE)
[1]  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
  • (?=^.{4}$): 字符串长度为 4。
  • (?=.*x)x 出现在字符串中的任何位置。

【讨论】:

    【解决方案2】:

    在您编辑的方法中使用 grepl(r 而不是 h):

    a<-c("hour","four","ruoh", "six", "high", "our")
    
    a[grepl(pattern="o", x=a) & grepl(pattern="u", x=a) & grepl(pattern="r", x=a) & nchar(a)==4]
    

    返回:

    [1] "hour" "four" "ruoh"
    

    【讨论】:

      【解决方案3】:

      您可以使用strsplitsetdiff,我在您的示例数据中添加了一个额外的边缘情况:

      a<-c("hour","four","ruoh", "six", "high", "our","oouh")
      a[nchar(a) == 4 &
        lengths(lapply(strsplit(a,""),function(x) setdiff(x, c("o","u","h")))) == 1]
      # [1] "hour" "ruoh"
      

      grepl

      a[nchar(a) == 4 & !rowSums(sapply(c("o","u","h"), Negate(grepl), a))]
      # [1] "hour" "ruoh" "oouh"
      

      sapply(c("o","u","h"), Negate(grepl), a) 给你一个矩阵,其中单词不包含每个字母,然后rowSums 的行为就像any 按行应用,因为它将被强制为逻辑。

      【讨论】:

      • 这可能需要根据您要如何处理某些极端情况进行调整(例如多个“h”)
      • 非常感谢@Moody_Mudskipper 你有 grepl 解决方案吗?
      猜你喜欢
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2015-11-18
      • 2010-09-15
      • 1970-01-01
      • 2022-01-17
      • 2015-01-31
      相关资源
      最近更新 更多