我正在寻找正确的表达式,用于搜索一个字符串,如果它只包含数字(0-9)或其他字符,则返回 true/false。
目前我有以下内容:
> teststring <- "012345c6789"
> any(str_detect(teststring,c(letters,LETTERS)))
[1] TRUE
但是这只检查字母,我想要正确的表达式来检查字符串中是否有任何字符不是数字。
我们可以使用模式[^0-9]+
,并结合grepl
函数从字符串开头(^
)到结尾($)
匹配一个或多个非数字元素。
grepl('^[^0-9]+$', teststring)
你可以尝试不使用正则表达式,仅通过转换为数字来实现:
containsOnlyNumbers = function(x) !is.na(as.numeric(x))
str1 <- "012345c6789"
str2 <- "016789"
#> containsOnlyNumbers(str1)
#[1] FALSE
#Warning message:
#In containsOnlyNumbers(str1) : NAs introduced by coercion
#> containsOnlyNumbers(str2)
#[1] TRUE
这将对你有用
teststring <- "012345c6789"
teststring1 <- "0123456789"
> suppressWarnings({is.na(as.numeric(teststring))})
> TRUE
> uppressWarnings({is.na(as.numeric(teststring1))})
> FALSE
!
来编辑你的答案,因为你想在第一种情况下得到 FALSE
,在第二种情况下得到 TRUE
。即使有20秒的时间差,我也会删除我的答案以避免重复。 - Colonel BeauvelTRUE
。 - Paul你可以否定这个模式。
!grepl('[0-9]|^$', string)