Skip to content

Instantly share code, notes, and snippets.

@ateucher
Created October 16, 2015 21:50
Show Gist options
  • Save ateucher/07732266a11bdd8f6f9d to your computer and use it in GitHub Desktop.
Save ateucher/07732266a11bdd8f6f9d to your computer and use it in GitHub Desktop.
Find matching parens in a string
find_matching_paren <- function(str, open_paren = "(") {
close_paren <- switch(open_paren, "(" = ")", "{" = "}", "[" = "]")
# Split string into single characters
str <- strsplit(str, "")[[1]]
## Find the first openening parenthesis in the string
start_pos <- grep(paste0("\\", open_paren), str)[1] + 1
counter <- 1
while (counter > 0) {
for (pos in start_pos:length(str)) {
char <- str[pos]
if (char == open_paren) {
counter <- counter + 1
} else if (char == close_paren) {
counter <- counter - 1
}
}
}
pos
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment