检查字符串是否仅包含数字或仅包含字符(R)

时间:2017-04-03 22:45:44

标签: r regex

我有这三个字符串:

letters

如何检查这些字符串中的哪一个仅包含字母或仅包含数字(在R中)?

numbers只应在LETTERS ONLY中检查

mix只应在NUMBERS ONLY检查

中为TRUE

grepl("[A-Za-z]", letters) 在任何情况下都应该是假的

我现在尝试了几种方法,但它们中没有一种对我有效:(

例如,如果我使用

letters

它适用于mix,但它也适用于.git/hooks/pre-commit,我不想要的。

提前致谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:6)

你需要坚持你的正则表达式

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

答案 2 :(得分:-1)

使用 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:]+$")