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

Fel*_*ann 7 regex r

我有这三个字符串:

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)

  • Numbers_only 仅适用于整数。如果您想在测试中包含分数,我建议使用 `numbers_only &lt;- function(x) suggestWarnings(!is.na(as.numeric(as.character(k))))`,如下所述:https:// stackoverflow.com/questions/24129124/如何确定字符向量是否有效数字或整数向量?noredirect=1&amp;lq=1 (2认同)

Mik*_*ung 8

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

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)


Jef*_*ker 7

使用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)