Tlatwork
Tlatwork

Reputation: 1525

How to extract string match within brackets in R?

I want to extract "a", "b" from ["a", "b"], where the Content within [...] is not known before doing the Operation. So [...] is the only identifier.

Normally, the extraction works like

stringr::str_match(string = ["a", "b"]', pattern = "LEFT(.*?)RIGHT")

So i have to find sthg along:

stringr::str_match(string = '["a", "b"]', pattern = "[(.*?)]")

but have to escape the brackets i guess.

stringr::str_match(string = '["a", "b"]', pattern = "[[](.*?)[]]")

Probably, now the brackets are escaped, but not (.*?)?

What i tried:

Upvotes: 1

Views: 2108

Answers (2)

akrun
akrun

Reputation: 886978

We can use str_replace which would directly extract the elements

library(stringr)    
str_replace(str2, "\\[([^]]+)\\].*", "\\1")
#[1] "\"a\", \"b\""

Or with str_match

str_match(str2, "\\[([^]]+)")[,2]
#[1] "\"a\", \"b\""

data

str2 <- '["a", "b"]'

Upvotes: 1

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

You can also use str_extractand positive lookbehind and lookahead:

str_extract(str1, "(?<=\\[).*(?=\\])")

Upvotes: 2

Related Questions