假设我有一个这样的字符串: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 添加检查时才开始。
最佳答案
请您尝试以下操作:
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.
关于r - 匹配字符范围内的元素 n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51811215/