Reputation: 531
I would like to check if a string contain only one type of character
For example
INPUT:
str = "AAAAB"
char = "A"
OUTPUT:
str contains only char = FALSE
With grepl(char,str)
the result is TRUE but I want it to be FALSE.
Many thanks
Upvotes: 5
Views: 1359
Reputation: 92300
Using gregexpr
char = "A"
str = "AAAA"
length(unlist(gregexpr(char, str))) == nchar(str)
## [1] TRUE
str = "ABAAA"
length(unlist(gregexpr(char, str))) == nchar(str)
## [1] FALSE
Upvotes: 3
Reputation: 70326
If you want to check for a specific character (in char
):
str <- "AAAAB"
char = "A"
all(unlist(strsplit(str, "")) == char)
#[1] FALSE
str <- "AAAA"
char = "A"
all(unlist(strsplit(str, "")) == char)
#[1] TRUE
Or, if you want to check if the string contains only one unique character (any one):
str <- "AAAAB"
length(unique(unlist(strsplit(str, "")))) == 1
#[1] FALSE
str = "AAAA"
length(unique(unlist(strsplit(str, "")))) == 1
#[1] TRUE
Upvotes: 5
Reputation: 121608
Another option is to use charToRaw
and check if it is unique:
xx <- "AAAAB"
length(unique(charToRaw(xx))) ==1
[1] FALSE
Upvotes: 4
Reputation: 193667
You can use the stri_count
from the "stringi" package, like this:
library(stringi)
stri_count_fixed(str, char) == nchar(str)
# [1] FALSE
Upvotes: 3
Reputation: 24218
You need to use not
operator for regex, in your case this would be:
> !grepl("[^A]", "AAA")
[1] TRUE
> !grepl("[^A]", "AAAB")
[1] FALSE
With variables:
grepl(paste0("[^", char, "]"), srt)
Upvotes: 4