我有这三个字符串:
letters <- "abc"
numbers <- "123"
mix <- "b1dd"
Run Code Online (Sandbox Code Playgroud)
如何检查这些字符串中的哪一个仅包含字母或仅包含数字(在R中)?
letters 只应在LETTERS ONLY检查中为TRUE
numbers 只应在NUMBERS ONLY检查中为TRUE
mix 在任何情况下都应该是假的
我现在尝试了几种方法,但它们都没有真正起作用:(
例如,如果我使用
grepl("[A-Za-z]", letters)
Run Code Online (Sandbox Code Playgroud)
它适用于letters,但它也适用于mix我不想要的.
提前致谢.
Tim*_*man 16
# 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
Run Code Online (Sandbox Code Playgroud)
你需要坚持你的正则表达式
all_num <- "123"
all_letters <- "abc"
mixed <- "123abc"
grepl("^[A-Za-z]+$", all_num, perl = T) #will be false
grepl("^[A-Za-z]+$", all_letter, perl = T) #will be true
grepl("^[A-Za-z]+$", mixed, perl=T) #will be false
Run Code Online (Sandbox Code Playgroud)
使用stringr包
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:]+$")
Run Code Online (Sandbox Code Playgroud)