Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have these three strings:

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

How can I check which one of these strings contains LETTERS ONLY or NUMBERS ONLY (in R)?

letters should only be TRUE in the LETTERS ONLY check

numbers should only be TRUE in the NUMBERS ONLY check

mix should be FALSE in every situation

I tried several approaches now but none of them really worked for me :(

For example if I use

grepl("[A-Za-z]", letters) 

It works well for letters, but it would also works for mix, what I don't want.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
808 views
Welcome To Ask or Share your Answers For Others

1 Answer

# 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...