new ruser
2007-May-13 20:26 UTC
[R] extracting text contained in brackets ("[ ... ]") from a character string?
I have a text string that contains text within two brackets. e.g. "testdata[3]" "testdata[-4]", "testdata[-4g]", I wish to "extract" the string enclosed in brackets? What is a good way to do this? e.g. fun(testdata[3]) = '3' fun(testdata[-4g]) = '-4g' --------------------------------- Moody friends. Drama queens. Your life? Nope! - their life, your story. [[alternative HTML version deleted]]
jim holtman
2007-May-13 21:35 UTC
[R] extracting text contained in brackets ("[ ... ]") from a character string?
here is one way using 'sub':> x <- c("testdata[3]", "testdata[-4]", "testdata[-4g]") > sub(".*\\[(.*)\\].*", "\\1", x, perl=TRUE)[1] "3" "-4" "-4g"> x.func <- function(x){ sub(".*\\[(.*)\\].*", "\\1", x, perl=TRUE)} > x.func(x)[1] "3" "-4" "-4g">On 5/13/07, new ruser <newruser at yahoo.com> wrote:> I have a text string that contains text within two brackets. > > e.g. "testdata[3]" "testdata[-4]", "testdata[-4g]", > > I wish to "extract" the string enclosed in brackets? > > What is a good way to do this? > > e.g. > > fun(testdata[3]) = '3' > > fun(testdata[-4g]) = '-4g' > > --------------------------------- > Moody friends. Drama queens. Your life? Nope! - their life, your story. > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > 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. >-- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem you are trying to solve?
Gabor Grothendieck
2007-May-13 22:45 UTC
[R] extracting text contained in brackets ("[ ... ]") from a character string?
If you know its of the form testdata[3] then this is sufficient x <- c("testdata[3]", "testdata[-4]", "testdata[-4g]") gsub(".*\\[|\\]", "", x) # c("3", "-4", "-4g") Here is a somewhat more general solution: library(gsubfn) x <- c("a[b]c[d]d", "[a]b") strapply(x, "\\[([^]]*)\\]", back = -1) # list(c("b", "d"), "a") On 5/13/07, new ruser <newruser at yahoo.com> wrote:> I have a text string that contains text within two brackets. > > e.g. "testdata[3]" "testdata[-4]", "testdata[-4g]", > > I wish to "extract" the string enclosed in brackets? > > What is a good way to do this? > > e.g. > > fun(testdata[3]) = '3' > > fun(testdata[-4g]) = '-4g' > > --------------------------------- > Moody friends. Drama queens. Your life? Nope! - their life, your story. > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > 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. >