In ruby, get content in brackets

regex, ruby

Solution

Usually `sub` is used for sub-stitutions. What you need is `scan`:

test = "Eclipse Developments (Scotland) Ltd t/a Martin & Co (Glasgow South)"

test.scan(/\(([^\)]+)\)/).last.first
# => "Glasgow South"

The reason for the odd `.last.first` call is `scan` returns an array of arrays by default. You want the first (and only) element of the last match.

Translating that regexp, which can be prickly for the uninitiated:

\(     # A literal bracket followed by...
(      # (Memorize this)
[^)]+  # One or more (+) characters not in the set of: closing-bracket [^)]
)      # (End of memorization point)
\)     # ...and a literal closing bracket.

Problem

I have the following string: Eclipse Developments (Scotland) Ltd t/a Martin & Co (Glasgow South) I need to get the last (always the last, however sometimes the only) brackets value, so in this case "Glasgow South". I know I should use `.sub` but can't work out the correct regex.

Original source