Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains anything but numbers

Tags:

string

r

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.

like image 215
Sebastian Avatar asked Dec 02 '22 16:12

Sebastian


2 Answers

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)
like image 70
akrun Avatar answered Dec 21 '22 08:12

akrun


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
like image 26
Colonel Beauvel Avatar answered Dec 21 '22 08:12

Colonel Beauvel