Skip to content
Prev 379942 / 398500 Next

reg expr that retains only bracketed text from strings

Hi Nevil,
In case you are still having trouble with this, I wrote something in R
that should do what you want:

mystrings<-c("ABC","A(B)C","AB[C]","<A>BC","{AB}C")

get_enclosed<-function(x,left=c("(","[","<","{"),right=c(")","]",">","}")) {
 newx<-rep("",length(x))
 for(li in 1:length(left)) {
  for(xi in 1:length(x)) {
   lp<-regexpr(left[li],x[xi],fixed=TRUE)
   rp<-regexpr(right[li],x[xi],fixed=TRUE)
   if(lp > 0 && rp > 0)
    newx[xi]<-substr(x[xi],lp+1,rp-1)
  }
 }
 return(newx)
}
get_enclosed(mystrings)

Jim

On Thu, Jun 13, 2019 at 12:32 AM William Dunlap via R-help
<r-help at r-project.org> wrote: