2017-04-03 107 views
1

我有這三個字符串:檢查字符串只包含數字或只允許字符(R)

letters <- "abc" 
numbers <- "123" 
mix <- "b1dd" 

如何檢查這些字符串中的一個由字母ONLY或數字,只在(R)?

letters只應在字母TRUE只檢查

numbers只應TRUE中顯示的數字僅檢查

mix應該是假的在任何情況下

我現在嘗試了幾種方法,但沒有他們真的爲我工作:(

例如,如果我使用

grepl("[A-Za-z]", letters) 

它適用於letters,但它也適用於mix,我不想要的。

在此先感謝。

回答

3

你需要堅持你的正則表達式

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 
+0

感謝您的快速響應。爲我工作得很好! –

+0

'perl = TRUE'沒有必要。 –

+0

我只是爲了安全@fexjoo如果它回答你的需要,那麼請選擇我的答案關閉Q –

7
# 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 
+0

感謝您的快速響應!也適用於我:) –