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.
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.
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.
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!
# 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With