Hi Nevil, Here's one way to do it. (No doubt some regular-expression-gurus will have more concise ways to get the job done.)
a1 <- sub(".*\\(","\\(",mystrings) a2 <- sub("\\).*","\\)",a1) a2[grep("\\(",a2,invert=TRUE)] <- "" a2 HTH, Eric On Wed, Jun 12, 2019 at 8:46 AM nevil amos <nevil.a...@gmail.com> wrote: > Hi > > I am trying to extract only the text contained in brackets from a vector of > strings > not all of the strings contain closed bracketed text, they should return an > empty string or NA > > this is what I have at the moment > > > mystrings<-c("ABC","A(B)C","AB(C)") > > substring(mystrings, regexpr("\\(|\\)", mystrings)) > > > #this returns the whole string if there are no brackets. > [1] "ABC" "(B)C" "(C)" > > > # my desired desired output: > # [1] "" "(B)" "(C)" > > many thanks for any suggestions > Nevil Amos > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.