1

I'm sure this is a duplicate, but I can't find it.

The closest I've found so far is:

Extract info inside all parenthesis in R

I am wanting to extract from a string any match that starts with a [, ends with a ], and has a + plus between those brackets. The regular expression I've put together based on a previous answer is a little too greedy.

library(magrittr)

str <- "[a] , [a + b] + [b] , [b - q] , [d - e + f]"

gregexpr(pattern = "(?=\\[).*?[+].*?(?<=\\])",
         text = str,
         perl = TRUE) %>%
  regmatches(x = str,
             m = .)

This returns

[[1]]
[1] "[a] , [a + b]"               "[b] , [b - q] , [d - e + f]"

where what I want is

[[1]]
[1] "[a + b]"               "[d - e + f]"
Community
  • 1
  • 1
Benjamin
  • 16,897
  • 6
  • 45
  • 65
  • What do you want it to return in cases like "[a - [b + c]]" or "[a + [b - c]] , [a]"? – LarsH Jan 13 '17 at 17:03
  • I hadn't thought about nesting, but Tot's answer is sufficient for my need to disallow `+` between brackets. – Benjamin Jan 13 '17 at 17:09

1 Answers1

2

How about:

\\[[^]+]+[+][^]]+\\]
Toto
  • 89,455
  • 62
  • 89
  • 125