Created
October 16, 2015 21:50
-
-
Save ateucher/07732266a11bdd8f6f9d to your computer and use it in GitHub Desktop.
Find matching parens in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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