代码之家  ›  专栏  ›  技术社区  ›  Steven M. Mortimer

匹配字符范围中的元素n次

  •  4
  • Steven M. Mortimer  · 技术社区  · 8 年前

    id = "ce91ffbe-8218-e211-86da-000c29e211a0"

    我可以在R中编写哪些正则表达式来验证此字符串的长度是36个字符,并且只包含字母、数字和破折号?

    文档中没有关于如何使用字符范围的内容(例如。 [0-9A-z-] )用量词(例如。 {36} TRUE 不管量词是什么。我肯定我遗漏了一些简单的东西。。。

    id <- "ce91ffbe-8218-e211-86da-000c29e211a0"
    
    grepl("[0-9A-z-]{36}", id)
    #> [1] TRUE
    
    grepl("[0-9A-z-]{34}", id)
    #> [1] TRUE
    

    只有当我在字符范围内添加数字0-9的检查时,此行为才开始。

    3 回复  |  直到 8 年前
        1
  •  2
  •   Paolo    8 年前

    您要使用:

    ^[0-9a-z-]{36}$
    
    • ^ 断言行的开始位置。
    • [0-9a-z-] - .
    • {36} 匹配前面的模式36次。
    • $

    试试看 here .

        2
  •  3
  •   RavinderSingh13 Nikita Bakshi    8 年前

    你能试一下吗

    grepl("^[0-9a-zA-Z-]{36}$",id)
    

    或者

    grepl("^[[:alnum:]-]{36}$",id)
    

    运行之后,我们将得到以下输出。

    grepl("^[0-9a-zA-Z-]{36}$",id)
    [1] TRUE
    

    此处添加以下内容仅供说明之用。

    grepl("        ##using grepl to check if regex mentioned in it gives TRUE or FALSE result.
    ^              ##^ means shows starting of the line.
    [[:alnum:]-]   ##Mentioning character class [[:alnum:]] with a dash(-) in it means match alphabets with digits and dashes in regex.
    {36}           ##Look for only 36 occurences of alphabets with dashes.
    $",            ##$ means check from starting(^) to till end of the variable's value.
    id)            ##Mentioning id value here.
    
        3
  •  1
  •   Rui Barradas    8 年前

    如果字符串在目标字符之前或之后可以有其他字符,请尝试

    id <- "ce91ffbe-8218-e211-86da-000c29e211a0"
    grepl("^[^[:alnum:]-]*[[:alnum:]-]{36}[^[:alnum:]-]*$", id)
    #[1] TRUE
    
    grepl("^[^[:alnum:]-]*[[:alnum:]-]{34}[^[:alnum:]-]*$", id)
    #[1] FALSE
    

    id2 <- paste0(":+)!#", id)
    
    grepl("^[^[:alnum:]-]*[[:alnum:]-]{36}[^[:alnum:]-]*$", id2)
    #[1] TRUE
    
    grepl("^[^[:alnum:]-]*[[:alnum:]-]{34}[^[:alnum:]-]*$", id2)
    #[1] FALSE