-4

Suppose you want to reverse a string that parts sectioned off by parentheses and parts that aren't. What would be the best possible regex method to approach this? Here is a link to my last question addressing a similar issue R regex - splitting between parentheses

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
rev_x
"(A|C|G)(A|C|G|T)(A|C|G|T)(C|T)CCG(A|C|G|T)(A|C|G|T)(A|C|G|T)(A|C|G|T)(A|C|G|T)(C|T)GA(A|C|T)"
Community
  • 1
  • 1
alki
  • 3,334
  • 5
  • 22
  • 45
  • @akrun so the question is about how to reverse a vector? then close as a duplicate – rawr Aug 19 '15 at 04:18
  • @akrun here ya go http://stackoverflow.com/questions/18933441/how-to-reverse-order-a-vector – rawr Aug 19 '15 at 04:25

1 Answers1

3

You may also try stri_extract_all from library(stringi) to extract the characters along with the parentheses as a group (\\([^)]+\\)) or (|) any other character (.) in a list with a single list element, which can we extract with [[1]], then reverse the vector (rev) and paste it with collapse=''

library(stringi)
paste(rev(stri_extract_all(x, regex='\\([^)]+\\)|.')[[1]]), collapse='')
#[1] "(A|C|G)(A|C|G|T)(A|C|G|T)(C|T)CCG(A|C|G|T)(A|C|G|T)(A|C|G|T)(A|C|G|T)(A|C|G|T)(C|T)GA(A|C|T)"
akrun
  • 874,273
  • 37
  • 540
  • 662