Suppose I have a string x
and I want to split it like so:
x <- "(A|C|T)AG(C|T)(A|C|G|T)(A|C|G|T)(A|C|G|T)(A|C|G|T)(A|C|G|T)GCC(C|T)(A|C|G|T)(A|C|G|T)(A|C|G)"
# Desired output
[1] "(A|C|T)" "A" "G" "(C|T)" "(A|C|G|T)" "(A|C|G|T)" "(A|C|G|T)"
[8] "(A|C|G|T)" "(A|C|G|T)" "G" "C" "C" "(C|T)" "(A|C|G|T)"
[15] "(A|C|G|T)" "(A|C|G)"
I am using this splitting function, but I'm unable to split the strings not in the parenthesis. What would be the best way to approach this regex problem?
splitme <- function(x) {
x <- unlist(strsplit(x, "(?=\\()", perl=TRUE))
x <- unlist(strsplit(x, "(?<=\\))", perl=TRUE))
for (i in which(x=="(")) {
x[i+1] <- paste(x[i], x[i+1], sep="")
}
x[-which(x=="(")]
}
splitme(x)
[1] "(A|C|T)" "AG" "(C|T)" "(A|C|G|T)" "(A|C|G|T)" "(A|C|G|T)" "(A|C|G|T)" "(A|C|G|T)" "GCC"
[10] "(C|T)" "(A|C|G|T)" "(A|C|G|T)" "(A|C|G)"