We have a free text:
sal{del{rf}ghladfs}wds{w12rf}qq
Output should be:
salwdsqq
Please share various approaches if possible. For example : lapply, gsub, for/while loop, grep
We have a free text:
sal{del{rf}ghladfs}wds{w12rf}qq
Output should be:
salwdsqq
Please share various approaches if possible. For example : lapply, gsub, for/while loop, grep
This works in R
string1 <- "sal{del{rf}ghla}dfs}wds{w12rf}qq"
string2 <- gsub("{[^{}}]*}", "", string1, perl = TRUE)
string3 <- gsub("{.*}", "", string2, perl = TRUE)
string3
I think this would work whether you had balanced or unbalanced brackets:
unbalanced (as in the q)
x <- "sal{del{rf}ghla}dfs}wds{w12rf}qq "
paste0(gsub('\\w+}|[{} ]', '', strsplit(x, '\\{\\w+')[[1]]), collapse = '')
# [1] "salwdsqq"
inserted one randomly
x <- "sal{del{{rf}ghla}dfs}wds{w12rf}qq "
paste0(gsub('\\w+}|[{} ]', '', strsplit(x, '\\{\\w+')[[1]]), collapse = '')
# [1] "salwdsqq"
You can do this using a recursive regular expression.
x <- 'sal{del{rf}{sfddfdffdf}ghladfs}wds{w12rf}qq'
gsub('{(?:[^{}]+|(?R))*+}', '', x, perl=TRUE)
# [1] "salwdsqq"