Using R to parse and return text in brackets

Let's say I have a line:

x <- "This is a string (Yay, string!)" 

I would like to parse a string and return "Yay, string!"

How should I do it?

I tried a bunch of grep / grepl / gsub / sub / etc, but couldn't find the right combination of regular expressions or arguments. Sigh. I need to work on regular expression skills.

+5
source share
3 answers

Here are two ways to do this:

One: Find the desired string and replace the entire string with the bit that was found. (Known as trackback)

gsub(".*\\((.*)\\).*", "\\1", x)
[1] "Yay, string!"

This works because:

  • You use the backlink \\1to refer to the matched string in parentheses(.*)
  • , \\( \\).

: , , :

gsub(".*\\(|\\).*", "", x)
[1] "Yay, string!"

, | OR.

+7

, , , regex gregexpr() regmatches():

x <- "This is (a) string (Yay, string!)" 
pat <- "(?<=\\()([^()]*)(?=\\))"
regmatches(x, gregexpr(pat, x, perl=TRUE))
# [[1]]
# [1] "a"            "Yay, string!"
+4

qdap version 1.1.0 :

library(qdap)
x <- "This is a string (Yay, string!)" 

bracketX(x)
bracketXtract(x)

:

> bracketX(x)
[1] "This is a string"
> bracketXtract(x)
[1] "Yay, string!"

, , qdap .

: Josh...

> x <- "This is (a) string (Yay, string!)" 
> bracketX(x)
[1] "This is string"
> bracketXtract(x)
[1] "a"            "Yay, string!"
+2

All Articles