library(stringr)
toomp <- function(x) {
x <- str_replace_all(x, "\\(\\)", "")
if(str_length(x) == 0)
return(NULL)
last <- ""
new <- str_c(str_extract_all(x, "[a-z]")[[1]], collapse = "")
stopit <- str_length(new)
repeat {
full <- str_extract(x, "[\\(][a-z]+[\\)]")
nopar <- str_extract(full, "[a-z]+")
fullregex <- str_replace_all(full, c("\\(" = "\\\\(",
"\\)" = "\\\\)"))
x <- str_replace(x, fullregex, nopar)
if(last != full) {
new <- str_replace_all(new, str_sub(nopar, 1, 1), str_sub(full, 1, 2))
new <- str_replace_all(new, str_sub(nopar, -1, -1), str_sub(full, -2, -1))
}
last <- full
if(stopit == str_length(x))
break
}
return(cat(new, "\n"))
}
toomp("((a((bc)(de)))f)")
toomp("(((zbcd)(((e)fg))))")
toomp("ab((c))")
toomp("()")
toomp("((fgh()()()))")
toomp("()(abc())")
bGlicmFyeShzdHJpbmdyKQoKdG9vbXAgPC0gZnVuY3Rpb24oeCkgewogIHggPC0gc3RyX3JlcGxhY2VfYWxsKHgsICJcXChcXCkiLCAiIikKICBpZihzdHJfbGVuZ3RoKHgpID09IDApCiAgICByZXR1cm4oTlVMTCkKICBsYXN0IDwtICIiCiAgbmV3IDwtIHN0cl9jKHN0cl9leHRyYWN0X2FsbCh4LCAiW2Etel0iKVtbMV1dLCBjb2xsYXBzZSA9ICIiKQogIHN0b3BpdCA8LSBzdHJfbGVuZ3RoKG5ldykKICByZXBlYXQgewogICAgZnVsbCA8LSBzdHJfZXh0cmFjdCh4LCAiW1xcKF1bYS16XStbXFwpXSIpCiAgICBub3BhciA8LSBzdHJfZXh0cmFjdChmdWxsLCAiW2Etel0rIikKICAgIGZ1bGxyZWdleCA8LSBzdHJfcmVwbGFjZV9hbGwoZnVsbCwgYygiXFwoIiA9ICJcXFxcKCIsCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIlxcKSIgPSAiXFxcXCkiKSkKICAgIHggPC0gc3RyX3JlcGxhY2UoeCwgZnVsb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