Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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.

like image 351
Felix Grossmann Avatar asked Apr 03 '17 22:04

Felix Grossmann


People also ask

How do I check if a string contains only numbers?

Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/. test(str) . The test method will return true if the string contains only digits and false otherwise.

How can you check a string can only have alphabets and not digits?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.

How do I check if a string contains letters?

To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise. Copied!


1 Answers

# 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
like image 164
Tim Goodman Avatar answered Sep 22 '22 20:09

Tim Goodman