I'm searching for the right expression to search a string if it contains only numbers (0-9) or anything else and return true/false.
What I've got to is:
> teststring <- "012345c6789"
> any(str_detect(teststring,c(letters,LETTERS)))
[1] TRUE
But this only checks for letters, I want the right expression to check if any character is not a number in the string.
We can use the pattern to match only one or more non-numeric elements ([^0-9]+
) from start (^
) to the end ($)
of the string with grepl
.
grepl('^[^0-9]+$', teststring)
You can try without regex, just by converting to numeric:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With