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
How to Check if string contains certain characters in R. To check if a string contains certain characters or not, we can use the grepl () function in R language. R Programming A-Z: R For Data Science With Real Exercises! Here is an example that checks the ll characters in the Hello string.
Based on the previous output of the RStudio console we can see that the character “B” is located at the positions 15 and 25 within our character string x. The R programming language provides many alternative codes for the location of characters within strings.
The class of an object that holds character strings in R is “character”. A string in R can be created using single quotes or double quotes. chr = 'this is a string' chr = "this is a string" chr = "this 'is' valid" chr = 'this "is" valid' We can create an empty string with empty_str = "" or an empty character vector with empty_chr = character (0).
The functions as.character () and is.character () can be used to convert non-character objects into character strings and to test if a object is of type “character”, respectively. R has five main types of objects to store data: vector, factor, multi-dimensional array, data.frame and list.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With