Check if string contains ONLY NUMBERS or ONLY CHARACTERS (R)

you need to persist your regex

all_num <- "123"
all_letters <- "abc"
mixed <- "123abc"


grepl("^[A-Za-z]+$", all_num, perl = T) #will be false
grepl("^[A-Za-z]+$", all_letters, perl = T) #will be true
grepl("^[A-Za-z]+$", mixed, perl=T) #will be false

Using the stringr package

library(stringr)
all_num <- "123"
all_letters <- "abc"
mixed <- "123abc"

# LETTERS ONLY
str_detect(all_num, "^[:alpha:]+$")
str_detect(all_letters, "^[:alpha:]+$")
str_detect(mixed, "^[:alpha:]+$")

# NUMBERS ONLY
str_detect(all_num, "^[:digit:]+$")
str_detect(all_letters, "^[:digit:]+$")
str_detect(mixed, "^[:digit:]+$")

# Check that it doesn't match any non-letter
letters_only <- function(x) !grepl("[^A-Za-z]", x)

# Check that it doesn't match any non-number
numbers_only <- function(x) !grepl("\\D", x)

letters <- "abc" 
numbers <- "123" 
mix <- "b1dd"

letters_only(letters)
## [1] TRUE

letters_only(numbers)
## [1] FALSE

letters_only(mix)
## [1] FALSE

numbers_only(letters)
## [1] FALSE

numbers_only(numbers)
## [1] TRUE

numbers_only(mix)
## [1] FALSE

Tags:

Regex

R