Reputation: 1525
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:
Normally, i would escape the bracket [
like [[]
and use perl = TRUE. Therefore, i tried:
stringr::str_match(string = '["a", "b"]', pattern = "[[](.*?)[]]")
as shown above.
Use regex like /[^[\]]+\[[^[\]]+\]/
from Extract string between brackets
Upvotes: 1
Views: 2108
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\""
str2 <- '["a", "b"]'
Upvotes: 1
Reputation: 21400
You can also use str_extract
and positive lookbehind and lookahead:
str_extract(str1, "(?<=\\[).*(?=\\])")
Upvotes: 2