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
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
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
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)
Another option is to use charToRaw
and check if it is unique:
xx <- "AAAAB"
length(unique(charToRaw(xx))) ==1
[1] FALSE
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
You can use the stri_count
from the "stringi" package, like this:
library(stringi)
stri_count_fixed(str, char) == nchar(str)
# [1] FALSE