Sebastian
Sebastian

Reputation: 2570

Check if string contains anything but numbers

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

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174706

You may do negate the pattern..

!grepl('[0-9]|^$', string)

Upvotes: 1

akrun
akrun

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

Colonel Beauvel
Colonel Beauvel

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

Paul
Paul

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

Related Questions