[R] regexp inside and outside brackets

phgrosjean at sciviews.org phgrosjean at sciviews.org
Fri Dec 11 15:27:40 CET 2015


It depends the complexity of your expression. If you are sure you don’t have nested brackets, and pairs of brackets always match, this will take everything outside the brackets:

str <- "A1{0}~B0{1} CO{a2}NN{12}”
gsub("\\{[^}]*\\}", " ", str)

Philippe Grosjean


> On 11 Dec 2015, at 14:50, Adrian Dușa <dusa.adrian at unibuc.ro> wrote:
> 
> For the regexp aficionados, out there:
> 
> I need a regular expression to extract either everything within some
> brackets, or everything outside the brackets, in a string.
> 
> This would be the test string:
> "A1{0}~B0{1} CO{a2}NN{12}"
> 
> Everything outside the brackets would be:
> 
> "A1 ~B0 CO NN"
> 
> and everything inside the brackets would be:
> 
> "0 1 a2 12"
> 
> I have a working solution involving strsplit(), but I wonder if there is a
> more direct way.
> Thanks in advance for any hint,
> Adrian
> 
> -- 
> Adrian Dusa
> University of Bucharest
> Romanian Social Data Archive
> Soseaua Panduri nr.90
> 050663 Bucharest sector 5
> Romania
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at 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.



More information about the R-help mailing list