I have a question regarding to extract letters from a string For example I have in R one vector like:
America, Asia, Europe
I want to get all of the upper letters in this format like
AAE or A, A, E
How can I do this with regmatches and regexpr?
A simple gsub
x <- "America, Asia, Europe"
gsub("[^A-Z]","",x)
[1] "AAE"
SA, which might not be what the OP wants here. Always consider giving a flexible solution.grepl("A", x) to check.SA and that would be exactly what OP asked for.You could use gsub here:
x <- "America, Asia, Europe"
output <- gsub("\\b([A-Z])[a-z]+(?:,\\s*)?", "\\1", x)
output
[1] "AAE"
If you want a CSV string output of capital letters, then consider:
x <- "America, Asia, Europe"
output <- gsub("\\b([A-Z])[a-z]+(?:,\\s*)?", "\\1, ", x)
output <- sub(", $", "", output)
output
[1] "A, A, E"
grepl("A", "AAE", fixed=TRUE)
gsub("[a-z]+","",x)