Reputation: 2570
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.
Upvotes: 4
Views: 2874
Reputation: 887118
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)
Upvotes: 8
Reputation: 31171
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
Upvotes: 6
Reputation: 1355
this will work for you
teststring <- "012345c6789"
teststring1 <- "0123456789"
> suppressWarnings({is.na(as.numeric(teststring))})
> TRUE
> uppressWarnings({is.na(as.numeric(teststring1))})
> FALSE
Upvotes: 2