如何使用 Stringr 检查向量是否包含 R 中的数字?

R.K*_*Kim 3 regex r vector stringr

使用 R 语言。它表示意外的方括号和圆括号标记。该模式似乎也有效。我在这里做错了什么?

if (str_detect(c("Hello 241", "Whawt 602"), [0-9])) {
    print("Oh no!")
} else {
    print("Yay!")
}
Run Code Online (Sandbox Code Playgroud)

答案:“正则表达式周围没有引号”:它只检查第一个元素。如何检查向量中的所有元素?

Tim*_*sen 5

如果您想检查字符串中是否至少存在一个数字,那么您可以尝试使用以下命令:

str_detect(c("Hello 241", "Whawt 602"), ".*[0-9].*")
Run Code Online (Sandbox Code Playgroud)

或者也可能是这样:

str_detect(c("Hello 241", "Whawt 602"), "(?=.*[0-9]).*")
Run Code Online (Sandbox Code Playgroud)

如果您需要单独检查每个单词是否包含数字,请尝试以下操作:

input <- c("Hello 241", "Whawt 602")
output <- sapply(input, function(x) {
    words <- unlist(strsplit(x, "\\s+"))
    num_matches <- sapply(words, function(y) str_detect(y, ".*[0-9].*"))
    result <- length(words) == sum(num_matches)
    return(result)
})

if (sum(output) == 0) {
    print("Yay!")
}
else {
    print("Oh no!")
}
Run Code Online (Sandbox Code Playgroud)