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

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

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

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

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

1 Answer

0 votes
by (71.8m points)
# 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...