locbalpar2 {lazy.tools} | R Documentation |
Return the locations of the matching parentheses
Description
Return the locations of the matching parentheses
Usage
locbalpar2(expr, loc, line = 1, escape = 1, debug = 0)
Arguments
expr |
Input string vector. |
loc |
The starting or ending locations of the parentheses
in |
line |
line number |
escape |
= 0 not to escape parens with double backslashes. |
debug |
= 1 to print intermediate results |
Details
This is an expanded version of lazy.tools::locbalpar
which can handle a string vector input.
When expr
is a scalar string, better use lazy.tools::locbalpar
.
loc
must be positive and less than sum(nchar(exp))
.
When expr
is a string vector,
assuming that there are no length 0 elements of expr,
the location of the parens can be specified as follows:
Method 1 (with line
and loc
)
Suppose that the location of the paren of interest is in location
(chracter) LOC at line LINE. Then the following code will find
the location of the matching paren.
locbalpar2( expr, LOC, LINE )
Note that loc
and line
can be vectors of the same length.
Method 2 (with loc
)
In this case, loc
must be specified so that
unlist(strsplit(expr,""))[loc]
contains opening or closing parens.
This function returns line=0, locbp=0
.
The following characters are treated as parentheses:
"(", "{", "[", "<", ")", "}", "]", ">"
Value
A list of
line
the line number.
locbp
the locations of matching parens in the line.
Examples
# When counting characters, count the length 0 character, "", as 1.
# For example, consider the example below where
# expr1 has length 0 character, "", at lines 2 and 4 and
# expr2 has length 1 blank character, " ", at lines 2 and 4.
# The locations of parens for expr1 must be counted from expr2 as: \cr
# \code{unlist(strsplit(expr2,""))}\cr
# The two results below should be the same.
expr1 <- c( "1(", "", "4)(", "", "89)" )
expr2 <- c( "1(", " ", "4)(", " ", "89)" )
printm( expr1, expr2 )
exprc1 <- unlist(strsplit(expr1,""))
exprc2 <- unlist(strsplit(expr2,""))
printm( exprc1, exprc2 )
locbalpar2( expr2, c(2,3,2), c(1,3,3) )
locbalpar2( expr1, c(2,6,5) )
locbalpar2( expr2, c(2,6,5) )
# escape or not
locbalpar2( "a(b\\(d)",2 )
locbalpar2( "a(b\\(d)",2, escape=0 )
# Find the matching closing brace.
expr <- c(
"locbalpar2 <- function( expr, loc ){",
" # find the location of the balanced paren",
" # use standard version when expr is a string",
"",
" if( !is.vector(expr) ){",
" return( locbalpar( expr, loc ) )",
" }",
"",
"} # end of locbalpar2"
)
locbalpar2( expr, regexpr("{", expr, fixed=1 )[1] )
# find all "(" and their matching ")".
locs <- gregexpr("(", expr, fixed=TRUE )
LL <- NULL
for( i in 1:length(locs) ){
if( all( locs[[i]] < 0 ) ) next
LL <- rbind(LL,cbind(i,locs[[i]]))
}
locbalpar2(expr,LL[,2],LL[,1])